javascript concat() method adds newline randomly - javascript

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>

Related

Get value from hidden field - JavaScript

I have a <input type="hidden" class="Key" value="1m2.123.mds.34g" />
How can I get the value without using jQuery?
With jQuery i just only write:
var parse = $('.Key').attr("value")
alert(parse);
I need this in pure JavaScript, maybe use RegEx? I will execute this script on txt file which will contain such line.
check this
window.onload=function(){
var hidden=document.getElementsByClassName("Key");
alert(hidden[0].value);
}
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
var inputs = getElementsByClassName('Key');
for(var i=0; i<inputs.length;i++) {
console.log(inputs[i].value);
}
Easy! Just use getElementsByClassName. E.g:
document.getElementsByClassName('Key')[0].value
Or if you had to get the value by id you can use getElementById
document.getElementById('idHere').value
Here's 4 ways to get the value of .Key. Also I added a better way to do it in jQuery as well using the method val().
SNIPPET
var k = document.querySelector('.Key').value;
console.log(k);
// This works if .Key is inside a <form>
var e = document.forms[0].elements[0].value;
console.log(e);
var y = document.getElementsByTagName('input')[0].value;
console.log(y);
var s = document.getElementsByClassName('Key')[0].value;
console.log(s);
//BTW there's a better way of finding value with jQuery
var $Key = $('.Key').val();
console.log($Key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1'>
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
</form>
Thank you all. I resolve this problem as follow:
var regEx = /class="Name"+ value="(.*?)"/;
newName = result.match(regEx)[1];
var regEx2 = /class="Key"+ value="(.*?)"/;
var key = result.match(regEx2)[1];
Alert(key + ' ' + newName );

Needing to get only part of the ID everything after last underscore

I want to efficiently get everything after the last underscore or perhaps everything after and including "chk"
Example is
GridView1__ctl2_chkOut --> I want ONLY chkOut
Or
GridView1__ctl2_chkYes2 --> I want ONLY chkYes2
Or
GridView1__ctl2_chkNo2 --> I want ONLY chkNo2
I will always know the ID e.g. GridView1__ctl45_chkNo2
I know that a substring is probably not the best way to handle it unless it was used along with something else that counted characters till finding last underscore or perhaps it found the "chk" part etc.. not sure
var res = str.substring(1, 4);
HTML
<td>
<input id="GridView1__ctl2_chkOut" type="checkbox" name="GridView1:_ctl2:chkOut" checked="checked" class="out">
</td>
<td>
<input id="GridView1__ctl2_chkYes2" type="checkbox" name="GridView1:_ctl2:chkYes2" checked="checked" class="yesno">
</td>
<td>
<input id="GridView1__ctl2_chkNo2" type="checkbox" name="GridView1:_ctl2:chkNo2" class="yesno">
</td>
I would access the "id" attribute using jQuery and then split the value:
var r = $('.yesno').attr('id').split('_').pop()
fiddle
This will give you everything from last underscore to the end of string.
var res = str.substring(str.lastIndexOf('_')+1, str.length);
If you want to filter further i.e. anything before chk
var chkRes = res.substring(res.lastIndexOf('chk'), res.length);
You can just do this:
str='GridView1__ctl45_chkNo2';
let index = str.lastIndexOf('_');
let result = str.substr(index + 1);
fiddle: https://jsfiddle.net/75fc4uau/
Use split() and access the last item in the array
var ids = ['GridView1__ctl2_chkOut'
, 'GridView1__ctl2_chkYes2'
, 'GridView1__ctl2_chkNo2'
];
for (var i = 0; i < ids.length; i++) {
var splat = ids[i].split('_');
console.log(splat[splat.length - 1]);
}
var arr = "GridView1__ctl2_chkOut".split("_");
arr[arr.length - 1]; // gives chkOut

Add <span> to part of a label using jQuery

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)
});

getElementsByName with multiple input names

i'm making some auto sum input calculator for me, but i have problem, because i don't know how to select multiple inputs which have different names. I know i could just use 'input' instead of exact name, but i need to do calculations just for 5-6inputs not all, so please help me to do it this way..
Code looks now like this:
<script type="text/javascript">
function findTotal(){
var arr = document.getElementsByName('test1');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
So i would like to calculate exactly test1, test2, test3, test4, test5 inputs.
Thanks
You can use multiple attribute selectors with querySelectorAll():
var arr = document.querySelectorAll('[name="test1"], [name="test2"], [name="test3"], [name="test4"], [name="test5"]');
Though, if they share a common class name, you can select them by that:
<input name="test1" class="totaled">
<input name="test2" class="totaled">
<!-- etc. -->
var arr = document.querySelectorAll('.totaled');
Or, if they share a common parent element, you can find them from it:
<div id="the-parent">
<input name="test1">
<input name="test2">
<!-- etc. -->
</div>
var arr = document.querySelectorAll('#the-parent input');
// or
var arr = document.getElementById('the-parent').getElementsByTagName('input');

How to go about parsing text for keywords in jQuery?

Say I had a famous speech posted on a website. What would be the best way to go about searching for a given keyword, say 'hello' throughout the entire document and save the number of occurrences as an integer? I don't really know where to start on this one. Should I use something like...
var wordcount;
$('#wrapper').each(function(e)
{
$("div:contains('hello')"){ //all content will be in the wrapper div
wordcount++;
});
});
I know that probably isn't right, but hopefully I'm on the right track. Thanks for the help!
The easiest way is to just return the length of a RegExp match:
var count = $("#wrapper div:contains('hello')").html().match(/hello/ig).length;
var numberOfMatches = $('div').text().match(/hello/ig).length;
Well unfortunately, that div:contains is only going to fire once. It is looking for all divs that contain that text. Unless you have every word wrapped in a div tag...
var text = $('#wrapper').text();
var words[] = text.split(' ');
var count = 0;
for(var i=0; i<words.length; i++){ if(words[i].IndexOf("TheWord") >= 0){ count++; } }
This is a non jquery method, but it should work for you.
If you're wanting to do this interactively (i.e., with a dynamic string), then this implementation is idiomatic:
http://jsfiddle.net/entropo/S5uTg/
JS ...
$("#keyword").keyup(function() {
var value = $(this).val(),
re = new RegExp(value, 'ig'),
count = $("#speech").text().match(re).length;
$("#result").text("Occurences: " + count);
});
HTML ...
<div id="search-form">
<legend>Search through this text</legend>
<label for="keyword">Keyword</label>
<input id="keyword" name="keyword" type="search"
placeholder="e.g. - today" required="" autofocus="" />
<div id="result"></div>
</div>

Categories