Hi guys, I wonder if you can help me at all, I am a bit stuck here.
Having this HTML:
<div class="formWrapper">
<h2>Form box</h2>
<div class="unstyledForm">
<p>These form fields have minimal styles applied to it, so that tehy look the same in every browser and device</p>
<div class="row">
<label class="control-label" for="email">Email address<span class="mandatory"> *</span>
</label>
<div class="controls">
<input id="email" type="text">
</div>
</div>
<div class="row">
<label class="control-label" for="address">Address<span class="mandatory"> *</span>
</label>
<div class="controls">
<input id="address" type="text">
</div>
</div>
<div class="row">
<label class="control-label" for="memorableQuestion">Memorable question<span class="mandatory"> *</span>
</label>
<div class="controls">
<select id="memorableQuestion">
<option value="date">Memorable date</option>
<option value="pet">Memorable pet</option>
</select>
</div>
</div>
<div class="row">
<label class="control-label" for="address">Address 1
</label>
<div class="controls">
<input id="address" type="text">
</div>
</div>
</div>
</div>
I am trying to add a span with a class of noWrap around the last word and the asterisk, to prevent it from wrapping on the following line.
Now, the approach I was trying to use - which perhaps isn't the best one - was to first of all test whether the page has any label with an asterisk. If so look for the labels that contain the asterisk and add a span around them. Now, I didn't get past the first stage. Here is my script so far:
$(document).ready(function(){
//alert("ohi");
var isAsterisk = $(".mandatory").length;
console.log("isAsterisk " + isAsterisk);
if(isAsterisk){//if there are asterisks
var $asterisk = $(".row .control-label").find(".mandatory");//find the asterisk
var words = $asterisk.parents(".control-label").text().split(" ");//select the label with asterisk get the text and put each word in an array
for(var i = 0; i < words.length; i++){//print the array elements and their length
console.log("length of words for each element of array element " + words[i] + " is " + words[i].length);
}
//var lastWord = getLastWord(words);
//http://stackoverflow.com/questions/7075397/select-last-word-in-a-container
console.log("there are asterisks. Span selected are " + $asterisk.length + ", words are "+ words + "words needed are " + words[words.length - 1] + " and " + words[words.length - 2]);
}
});
The problem I am having is that I don't know how to select the asterisk and the word that comes before it for every element of the array. I mean I know that what I need are essentially words[words.length - 1]
and words[words.length - 2]
but how do I get them out? Any idea?
thanks