Add <span> to part of a label using jQuery - javascript

I'm trying to add a span to only part of a label using jQuery. I'm able to isolate the section I want to add the span to (view my fiddle and inspect via the console), but now that I've got that, I don't know how to add the actual span. I need this in order to style a specific section of the label (in this case "red" as an example). Unfortunately, the markup is dynamically generated, so I can't just manually add it.
Here's my fiddle.
Here are my watered-down code snippets if you'd prefer to view them here:
HTML:
<input type="checkbox" /><label> Some Number (XXXXXX1234)</label><br />
<input type="checkbox" /><label> Some Other Number (XXXXXX4567)</label><br />
<input type="checkbox" /><label> Some Number (XXXXXX7890)</label>
CSS:
span {
color: red;
}
JS:
var label = $('label');
$.each(label, function() {
var arr = $(this).text().split(' '),
num = arr[arr.length-1];
console.log(num);
});
This is what I'm starting with:
<input type="checkbox" /><label> Some Number (XXXXXX1234)</label><br />
And this is what I'm trying to achieve:
<input type="checkbox" /><label> Some Number <span>(XXXXXX1234)</span></label><br />
There will by multiple inputs throughout the site, hence $.each.
I've found partial answers to this dilemma on Stack Overflow, just not the right combination to complete the task.

Match it with a regex and insert the spans in strings returned to the html() function
$('label').html(function(_,html) {
return html.replace(/(\(.*?\))/, "<span>$1</span>");
});
FIDDLE
If you want to split on spaces and get the last part, you can do that instead
$('label').html(function(_,html) {
var parts = html.split(" ");
var last = parts.pop();
parts.push('<span>', last, '</span>');
return parts.join(" ");
});
FIDDLE

Finishing up the approach you started with: set the element text to everything before the last section, then append the span and its contents:
var label = $('label');
$.each(label, function() {
var el = $(this),
arr = el.text().split(' '),
num = arr[arr.length - 1],
rest = arr.slice(0, arr.length - 1).join(' ');
el.
text(rest + " ").
append($('<span>').text(num));
});
span {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" />
<label>Some Number (XXXXXX1234)</label>
<br />
<input type="checkbox" />
<label>Some Other Number (XXXXXX4567)</label>
<br />
<input type="checkbox" />
<label>Some Number (XXXXXX7890)</label>

Try the below working code snippet.I hope it will solve the issue
var label = $('label');
$.each(label, function() {
var arr = $(this).text().split(' '),
num = arr[arr.length-1], modifiedText = '<span>'+num+'</span>', finalText= $(this).text().replace(num, modifiedText);
$(this).html(finalText)
});

Related

how to get two word from a input field and make url based on another field

here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.
Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.
jQuery($ => {
$("#business_name").on('input', e => {
var text = $(e.target).val().trim().replace(/\s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
$("#business_url").val(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
After replacing certain characters with ' ' count the number of ' ' in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below:
$(document).ready(function() {
var count = 0;
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
count = (Text.split("-")).length - 1;
if (count == 2) {
return;
}
$("#business_url").val(Text);
});
});

How to get all labels and its input elements in javascript

I would like to get all labels and its input elements using Javascript.
I have also radio, checkboxes and textarea elements.
Then I want to put it in an array of objects.
This is what I have done,
var html = data;
var array = [];
for(var i=0;i<$("input").length;i++){
array[i] = {label:"",val:$("input").eq(i).val()};
}
console.log(array);
By the way, doesn't have for attributes and also their next sibling is not always the input/radio/checkbox/textarea element. Sometimes,the structures are,
<label>Something:</label><Br/ ><input type="text" />
How can I do what I want in this situation?
You can use map() method to generate the array and use prevAll() method with jQuery :first pseudo-class selector to get the label(you can't use prev() method since there is a br tag in between).
var array = $("input").map(function(){
return {
label : $(this).prevAll('label:first').text(),
val:$(this).val()
};
}).get();
console.log(array);
FYI : If the input is wrapped by label in some case then you can use closest() method to get the wrapped element. Although you can use :input to select all form elements.
var array = $(":input").map(function() {
return {
label: $(this).prevAll('label:first').text(),
val: $(this).val()
};
}).get();
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Some</label>
<Br/>
<input type="text" value="1" />
<label>Some1</label>
<Br/>
<input type="text" value="11" />
<label>Some2</label>
<Br/>
<input type="text" value="2" />
<label>Some3</label>
<Br/>
<input type="text" value="4" />
<label>Some4</label>
<Br/>
<input type="text" value="3" />
<label>Some422</label>
<Br/>
<select><option value="1"></option><select>
You're using labels wrong so I'm going to assume what you really want is just some identifying attribute of the text field checkbox etc to associate with the value.
Here is my go
https://jsfiddle.net/1akh5qg9/
HTML
<form id="test-form">
<label>Label1:</label>
<input class="get-value" name="input1" type="text" />
<br>
<label>Label2:</label>
<input class="get-value" name="input2" type="text" />
<br>
<label>Label3:</label>
<input class="get-value" type="checkbox" name="checkbox1">I have a bike
<br>
<br>
<button id="submit-button">Get Values</button>
</form>
Javascript
let btn = document.getElementById('submit-button');
let form = document.forms['test-form'].getElementsByClassName('get-value');
let valueArr = [];
// attach onclick handler
btn.onclick = function(e) {
e.preventDefault();
getFormValues();
}
// getFormValues
function getFormValues() {
for (var x of form){
valueArr.push({label:x.name ,value:x.value})
}
console.log(valueArr);
}
Results
[
{label:"input1", value:"test1"},
{label:"input2", value:"test1"},
{label:"checkbox1", value:"on"}
]
For you to get the label tags in your HTML form you first have to get the label tag from the DOM and follow up with the code below:
// get array of label tags in the DOM
const label = document.getElementsByTagName("label")
for (k = 0; k < label.length; k++){
const labelText = Array.prototype.filter
.call(label[k].childNodes, x => x.nodeName === "#text")
.map(x => x.textContent)
console.log(labelText)
}
If you want to select all elements (labels, inputs) into a single array, try using a custom attribute and use a selector like this $('*[data-all-labels-inputs]');
I would recommend doing something up-front in the HTML to mark the items you want to get.
You could put the label and input pairs in a DIV to indicate that they go together and then give the DIV a class that you could filter and loop on.
You could also use data-tag attributes to name the pairs. Say give all the labels and inputs the attribute data-LabelInp="NameA". Then you can select all labels with attribute data-LabelInp, get the value of the attribute and find the matching input with data-LabelInp === that value.

javascript concat() method adds newline randomly

I'm writing a JS code that reads the checkboxes in a particular , checks if they're selected, and if yes, appends their value to a string. This is the code that I have:
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str="";
for(var i =0; i< checkboxArr.length;i++){
var cb = checkboxArr[i];
if(cb.checked){
var newVal=cb.value;
str=str.concat(newVal);
str=str.concat(",");
}
}
alert(str);
The string that I get is:
value1
,value2
,value3
How are these newlines coming in the string ?
Also, the occurance of these newlines is random - sometimes they appear, sometimes I get the desired string.
I also tried combining the concat() calls into 1 statement, and I used the += operator as well, but no luck.
Any guidance is earnestly appreciated. Thanks
That's all you need. Use js right :D
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str = [];
checkboxArr.forEach(function(cb) {
if (cb.checked) str.push(cb.value);
});
alert(str.join(', '));
and if you still have the same result check your html code. It seems like you have line break right after your value in checkbox
check implementation with ES6, not sure why you are getting new line,
var btn = document.getElementById('btn');
btn.onclick = function(){
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]:checked');
var res = Array.from(checkboxArr).map(cb => cb.value.trim()).join(',')
console.log(res)
}
<div id="div_name">
<input type="checkbox" value="cb_1" />
<input type="checkbox" value="cb_2" />
<input type="checkbox" value="cb_3" />
<input type="checkbox" value="cb_4" />
<input type="checkbox" value="cb_5" />
</div>
<button id="btn">Check</button>

How to strike string in an html table using javascript?

Everytime i search for the word "Javascript" as specified in my code, I can't seem to get that word to be striked out in the table. I don't see why my input is not finding my word i'm searching through the ID.
<script type = "text/javascript">
<!--
function findWord(){
var str = document.getElementById("word").value;
var text = document.getElementById("search").innerHTML;
text = text.toLowerCase();
str = str.trim();
var n = str.indexOf(str.toLowerCase());
if( n != -1 )
{
text = text.replace( str , "<u>"+str+"</u>" );
}
text = text.toUpperCase();
document.getElementById("search").innerHTML = text;
}
<table>
<tr>
<td class="wordSearch" id="search">
QMGLUTKVRDIYKSA<br />
GKMTWRITELNXDYP <br />
MGETELEMENTBYID <br />
TTOLOWERCASEBRD <br />
NYRTOUPPERCASEI <br />
CJDYOFUNCTIONPN <br />
WEMSFZTJZJOMFTV <br />
BCBCCXSURWHILEE <br />
PPRETURNXATLJOU <br />
OIFYGTVFXHAAVIN <br />
FZRXADXETWINDOW <br />
DWNIZKHIVFXPIDL <br />
IFRSTRINGVCQQLP <br />
DOCUMENTULELSEN <br />
JYBOOLEANFAXAJH
</td>
</tr>
</table>
<form action="">
<p>
<label>Enter the word you've found and press Enter:
<input type="text" id="word" />
</label>
<input type="button" value="Enter" onclick= "findWord();" />
</p>
</form>
<div id="scoreArea"></div>
use a Jquery plug-in for filter and search in a table like jQuery.FilterTable
jQuery.FilterTable
this code may help you
function findWord(str) {
var tdText=document.getElementById("search").textContent.trim();
return tdText.search(str);
}
You've got a few errors here. The first one you'll find on debugging is:
Uncaught ReferenceError: str is not defined
This means you're trying to call the strike() function on a variable that hasn't been defined. You'll first need to get the search value and store it in a variable.
You're html has the input as id="word", so we need to get that from the html.
The command to do this is:
document.getElementById("word")
And we specifically want the value of what they typed in, which is:
var str = document.getElementById("word").value
Now if they type in "hello" or "javascript", it will be stored in the str variable. Problem number 1 fixed! Onto the second problem.
var inputVal = document.getElementById( "search" );
Remember, when you get an Element, it's returning the entire node, not the value stored within it. Before, we had to use the value command to get the actual text, but if you try that here, it won't work because search is a <td> element, not an input. I've never had to get text from a <td> before, so I had to look it up using the debugger tools. (If you're not familiar with them, here's a guide on how to use chrome's dev tools. As it turns out, for a td, what you want is either a innerText or innerHTML. Looking at what is stored in each, innerHTML is the one we would want to use as it gets just the entire html, which will be important later on (innerText doesn't get html elements like <br\>).
var wordSearch = document.getElementById("search").innerHTML;
I also, changed the name of the variable you were storing this in from inputVal to wordSearch as I feel like naming it inputVal is a bit confusing as I would presume by that name it was the value inputted by the user, not the value of the wordSearch document.
Ok, now we have the input from the user and the wordSearch, the next troublesome line is this one:
wordSearch.elements.value = words.indexOf( inputVal.value=result );
I believe you're trying to see if the value the user provided existed somewhere in the wordSearch, which would be the next logical step to take. So, there's a couple things here. Firstly, again you're referencing variables that haven't been defined, in this case: wordSearch. Based on your comment above, you were using wordSearch was from the class name. Unfortunately, in JavaScript, you can't directly call an element based on it's class like that. You would need to do something like:
document.getElementsByClassName("wordSearch")
However, I wouldn't recommend this method, because (as a canny observer may have guessed from the name) getElementsByClassName returns a list of elements, not a specific element (hence the name using "elements" not "element"). That's because multiple elements can have the same class name. That is why I used the id, instead of the class name to find it earlier. Only a single element can have a particular id.
Secondly, we have the following snippet of code:
words.indexOf( inputVal.value=result )
This is doing two things. First, it is assigning the results variable to inputVal.value because you have a single equals sign. If you wanted to compare them, you would need two (==) or three(===). The second thing it's doing is checking words for the first index of that value. indexOf return an integer indicating where it was found, and -1 if it wasn't found. Let's fix this.
var locationFound = wordSearch.indexOf(str.toUpperCase());
This will give us the location where the search value provided is found in the word search or -1 if it isn't found. Then you could do something like:
if (locationFound === -1) {
alert(str + " wasn't found");
} else {
// strike through code goes here
}
Now, we'd need to code up the strike through section.
var locationEnd = locationFound + str.length;
str = str.strike();
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
Ok, this may look a bit confusing, but let's walk through it one line at a time.
var locationEnd = locationFound + str.length;
This is getting the end point of where the search value was found, which we'll need in a bit.
str = str.strike();
This is where we do the strike through, replacing the original text.
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
What this is doing is removing the original word in the document, and replacing it with the struck through version. It's then setting that value to the innerHTML of the element with the id of search.
The final code:
<table>
<tr>
<td class="wordSearch" id="search">
QMGLUTKVRDIYKSA <br />
GKMTWRITELNXDYP <br />
MGETELEMENTBYID <br />
TTOLOWERCASEBRD <br />
NYRTOUPPERCASEI <br />
CJDYOFUNCTIONPN <br />
WEMSFZTJZJOMFTV <br />
BCBCCXSURWHILEE <br />
PPRETURNXATLJOU <br />
OIFYGTVFXHAAVIN <br />
FZRXADXETWINDOW <br />
DWNIZKHIVFXPIDL <br />
IFRSTRINGVCQQLP <br />
DOCUMENTULELSEN <br />
JYBOOLEANFAXAJH
</td>
</tr>
</table>
<form action="">
<p>
<label>Enter the word you've found and press Enter:
<input type="text" id="word" />
</label>
<input type="button" value="Enter" onclick= "findWord();" />
</p>
</form>
<div id="scoreArea"></div>
<script type="text/JavaScript">
var words = "Javascript";
function findWord() {
var str = document.getElementById("word").value.toUpperCase();
var wordSearch = document.getElementById("search").innerHTML;
var locationFound = wordSearch.indexOf(str);
if (locationFound === -1) {
alert(str + " wasn't found");
} else {
var locationEnd = locationFound + str.length;
str = str.strike();
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
}
}
</script>

How to remove a defined text character from element?

I need to remove y from the text character:
My mark up:
<label>
<input type="checkbox" name="_sft_category[]" value="" data-sf-cr="_sft_31" data-sf-hide-empty="1"> y2012 <span class="sf-count">(8)</span>
</label>
it has to become 2012 and I am trying the following but with no luck
$('label input').text(function() {
var text = $(this).text();
return text.indexOf('y') == 0 ? text.substring(1) : text;
});
There is a blank space in my text output, I wonder if that has something to do as it is " y2012 "
You are not setting value again in input
$('label input').text(function() {
var text = $(this).text();
text = text.replace('y','');
$(this).val(text);
});
Note: If you can change the original markup instead of fixing it using javascript that will be better.
In this case it is not the input element's text, it is the contents of a text node so
var $input = $('label input'),
elTxt = $input[0].nextSibling;
elTxt.nodeValue = elTxt.nodeValue.replace(/^(\s)?y/, '$1')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>
<input type="checkbox"> y2012
</label>
Use this:
return text.replace("y", "")

Categories