Jquery value integer with id through loop - javascript

I have a simple for loop:
for (var i = 0; i < 10; i++) {
$('#input' + i).on('blur', function() {
var values = $('#input' + i).val();
console.log(values);
});
}
I want to get the values of my #input, if I write something in my input I just get the message undefined in my console.
But Why if I run the following I get something correct ?
for (var i = 0; i < 10; i++) {
$('#input' + i).on('blur', function() {
var values = $('#input0').val();
console.log(values);
});
}
How do I put that values onto another id in that loop?

The problem seems to be that are missing elements. You can remove the for() loop, jQuery makes all for you:
$('[id^="input"').on('blur', function() {
var values = $(this).val();
console.log(values);
});
With this mode you can render all inputs you need and jQuery will loop through all of them without creating listeners to inexistent elements.

If you have really to use for loop try to separate the logic and you have to use event delegation .on() and use jQuery object $(this) inside the event because this object contain the current input blured :
for(var i = 0; i< 6; i++) {
$('body').on('blur', '#input'+i, getValue);
}
function getValue() {
var values = $(this).val();
console.log(values);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input0' value='0' />
<input id='input1' value='1' />
<input id='input2' value='2' />
<input id='input3' value='3' />
<input id='input4' value='4' />
<input id='input5' value='5' />
But it will be better if you could avoid the loop and add general class for all your inputs or use start-with selector ^=:
$("body").on('blur', '[id^='input']', function() {
var values = $(this).val();
console.log(values);
});
$('body').on('blur', '.input', function () {
var values = $(this).val();
console.log(values);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='input' id='input0' value='0' />
<input class='input' id='input1' value='1' />
<input class='input' id='input2' value='2' />
<input class='input' id='input3' value='3' />
<input class='input' id='input4' value='4' />
<input class='input' id='input5' value='5' />

The blur event will happen sometime in future when you will blur from that specific input.
At that time the i value will be changed, since the loop has finished execution i has most recent value.
You need to create a closure and bind this i to the blur event
for (var i = 0; i < 10; i++) {
(function(i){
$('#input' + i).on('blur', function() {
var values = $('#input' + i).val();
console.log(values);
});
}(i))
}
JSFIDDLE

Related

Return CheckBox True False Status With jQuery Map

I am creating dynamic CheckBoxes using jQuery and by default, those are set to false status. Something as follows:
<input type="checkbox" class="cbCheck" value="false" />
So you can see no value or id is assigned there. Is it possible to just retrieve the true/false based on CheckBox checked/unchecked status something as follows using jQuery mapping?
string = $('input[type=checkbox]:checked').map(function (i, elements) {
return elements; //Here the elements like true or false, instead of elements.value
});
alert(string.join(','));
Expected Output: true, false, false, true (Based on user selection)
You can use the checked property.
const string = Array.from($('input[type=checkbox]')).map(function(element) {
return element.checked; //Here the elements like true or false, instead of elements.value
});
console.log(string.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" checked/>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked/>
var checkboxes = [];
function createDynamicCheckBoxes() {
if (checkboxes.length != 0)
return;
var numberOfBoxes = parseInt(Math.random() * 10) + 1;
for (var i = 0; i < numberOfBoxes; i++) {
var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("value", "false");
var number = document.createElement('label');
number.innerText = "(" + (checkboxes.length+1) + ") ";
document.getElementById("container").appendChild(number);
document.getElementById("container").appendChild(checkbox);
document.getElementById("container").appendChild(document.createElement('br'));
checkboxes.push(checkbox);
}
}
function logValues(){
for(var i=0; i<checkboxes.length;i++){
console.log("Checkbox (" + (i+1) + ") is set to " + checkboxes[i].checked);
}
}
<button onclick="createDynamicCheckBoxes()">Generate Checkboxes</button>
<button onclick="logValues()">Log Values of Checkboxes</button>
<div id="container">
</div>
This is a pure JavaScript based snippet. You can do something like this!
The .checked property return check/uncheck status of checkbox. So you need to use it.
var string = $('[type=checkbox]').map(function (i, elements) {
return elements.checked;
}).toArray().join(",");
Also you can simplify the code
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
console.log(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked />
<input type="checkbox" class="cbCheck" />

Input number and display the Input Fields according to the number inputed

I want to display the number of input box according to the number inputed in the how many.
My code is not working
<input id="howmany" />
<div id="boxquantity"></div>
Jquery/JavaScript
$(function() {
$('#howmany').change(function(){
for(i=0; i < $("#howmany").value; i++)
{
$('#boxquantity').append('<input name="boxid[]" type="file" id="boxid[]" size="50"/>');
}
});
});
I think the problem with the code is it's using .value on a jquery object. I replaced the $("#howmany").value with $("#howmany").val()
I also added a remove function to clear the number of inputs displayed.
Do run the snippet, thanks
$(document).ready(function() {
$('#howmany').change(function() {
$("#boxquantity input").remove();
for (i = 0; i < $("#howmany").val(); i++) {
$('#boxquantity').append('<input name="boxid['+i+']" type="file" id="boxid['+i+']" size="50"/>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="howmany" />
<div id="boxquantity"></div>
Working code, without jQuery.
Built the HTML into a variable and then appended to the DOM in a single go.
var boxes = "";
document.getElementById("howmany").onchange = function() {
boxes = "";
var howmany = document.getElementById("howmany").value;
for(i=0;i<howmany;i++) {
boxes += '<b>File ' + i + '</b>: <input type="file" id="box' + i + ' name="box' + i + ' /><br/>';
}
console.log(boxes);
document.getElementById("boxquantity").innerHTML = boxes;
}
Here is a JSBin link.
Replace value with val. You can replace $("#howmany").value with $(this).val(). Also each input should have unique id
$(function() {
$('#howmany').change(function() {
for (let i = 0; i < $(this).val(); i++) {
$('#boxquantity').append('<input name="boxid[]" type="file" id="boxid[]_' + i + '" size="50"/>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="howmany" />
<div id="boxquantity"></div>
1st: use type="number" for input
2nd: for realtime use on('input',) instead of .change event .change works like .on('blur' ,)
3rd: use .val() instead of .value
4th: you need to reset the #boxquantity div when number is change .. for me it'll be better to save the inputs html to variable then use .html() instead of .append() .. OR you can use $('#boxquantity').html(''); before the for loop
$(document).ready(function() {
$('#howmany').on('input',function() {
var Inputs = '';
for (var i = 0; i < $("#howmany").val(); i++) {
Inputs += '<input name="boxid[]" type="file" size="50"/>';
}
$('#boxquantity').html(Inputs);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="howmany" />
<div id="boxquantity"></div>

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

need for loop with conditional continue

I need to "continue" based on a checkbox.
HTML:
<input type = "text" id = "E1" /><input type="checkbox" id="C1">
<input type = "text" id = "E2" /><input type="checkbox" id="C2">
<input type = "text" id = "E3" /><input type="checkbox" id="C3">
<input type = "text" id = "E4" /><input type="checkbox" id="C4">
JS:
for (var i=1; i<=4; i++) {
if ("$C" +i.checked == true) {continue;}
...;
}
</script>
continue is the correct keyword to use to achieve this. I suspect that the issue in your case is that the if statement is never true.
I think you want this:
// Add 1 to index first and then concatenate with "#C" to create jQuery id selector
if ($('#C' + (i + 1)).is(':checked')) { continue; }
Your if statement above is functionally equivalent (when checked) to:
if ("$Ctrue" == true) { continue; }
$C and the string value of the Boolean are concatenated.
Try this.
document.getElementById("test").addEventListener("click", function(){
for (var i=1; i<=4; i++) {
if($("#C"+i).is(':checked'))
continue;
console.log($("#E"+i).val())
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type = "text" id = "E1" /><input type="checkbox" id="C1">
<input type = "text" id = "E2" /><input type="checkbox" id="C2">
<input type = "text" id = "E3" /><input type="checkbox" id="C3">
<input type = "text" id = "E4" /><input type="checkbox" id="C4">
<button id="test" >Test</button>
In this case, it won't be logging the values for those inputs who don't have adjacent checkbox checked for example
$("#C" + i).prop('checked') gives you true if the i-th checkbox is checked.
NOTE:
The way you loop is not good as you always need to adjust your conditions if you add/remove inputs.
Also your for-loop condition was off as you begin at 1
for (var i = 1; i < 5; i++) {
if ($("#C" + i).prop('checked'))
continue;
console.log(i + ' unchecked');
// do some stuff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" id = "E1" /><input type="checkbox" id="C1" checked>
<input type = "text" id = "E2" /><input type="checkbox" id="C2">
<input type = "text" id = "E3" /><input type="checkbox" id="C3">
<input type = "text" id = "E4" /><input type="checkbox" id="C4">
What you should do is break up your logic so that your program is readable and you can express it in the higher-level terms
function getCheckboxes() {
const checkboxes = [];
for (let i = 1; i <5; ++i) {
checkboxes.push(document.getElementById(`E${i}`);
}
return checkboxes;
}
getCheckboxes()
.filter(checkbox => !checkbox.checked)
.forEach(checkbox => {
// do something with an unchecked checkbook
});
Your loop never gets run because there are no event listeners in your code. You need to have an event listener tied to your checkbox inputs. It would look like this:
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener( 'change', function() {
if(this.checked) {
// output button here
}
}

Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?
Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it:
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
function findCheckBoxes(el, check) {
for(var i=0;el.childNodes[i];i++)
{
var child = el.childNodes[i];
if (child.type=="checkbox")
{
child.checked = check;
}
if (child.childNodes.length > 0)
this.findCheckBoxes(child, check);
}
}
iterate through the form.elements collection and check .type == "checkbox".
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = elements[i];
if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}
Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:
for (var i = 0; i < document.myForm.elements.length; i++) {
if (document.myForm.elements[i].type == "checkbox") {
document.myForm.elements[i].checked = true;
}
}
If jQuery is an option you can do this rather easily.
See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)
Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):
function selectCheckBoxes(bChecked) {
var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
for (var i = 0; i < aCheckBoxes.length; i++) {
aCheckBoxes[i].checked = bChecked;
}
}
If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:
function selectCheckBoxes(bChecked) {
var oParent = document.getElementById('parentsID');
var aElements = oParent.getElementsByTagName('input');
for (var i = 0; i < aElements.length; i++) {
if (aElements[i].type == 'checkbox') {
aElements[i].checked = bChecked;
}
}
}
I would stick to the "class" method, however.
<html>
<head>
<script>
function selectCheckBox()
{
if(document.getElementById('id11').checked==true)
{
document.frm.id2.checked=true
document.frm.id3.checked=true
document.frm.id4.checked=true
}
if(document.getElementById('id11').checked==false)
{
document.frm.id2.checked=false
document.frm.id3.checked=false
document.frm.id4.checked=false
}
}
function selectCheckBox1()
{
if(document.getElementById('id12').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox2()
{
if(document.getElementById('id13').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox3()
{
if(document.getElementById('id14').checked==false)
{
document.frm.id1.checked=false
}
}
</script>
</head>
<body>
<form name="frm">
All :<input type="checkbox" id="id11" name="id1" value="1" onClick="selectCheckBox()"><br>
A. :<input type="checkbox" id="id12" name="id2" value="2" onClick="selectCheckBox1()"><br>
B. :<input type="checkbox" id="id13" name="id3" value="3" onClick="selectCheckBox2()"><br>
C. :<input type="checkbox" id="id14" name="id4" value="4" onClick="selectCheckBox3()"><br>
</form>
</body>
</html>

Categories

Resources