Updated after the hint in comments.
Current jsfiddle
Is there a way so that I only have to write the script once and use it for multiple ID's?
I currently have 3 checkboxes so I just copied the code 3 times but if I get for example a 100 checkboxes I can't imagine copying this a 100 times would be verry effecient
Current code
Javascript
var elem1 = document.getElementById('div_product_1'),
checkBox1 = document.getElementById('product_1');
checkBox1.checked = false;
checkBox1.onchange = function () {
elem1.style.display = this.checked ? 'block' : 'none';
};
checkBox1.onchange();
var elem2 = document.getElementById('div_product_2'),
checkBox2 = document.getElementById('product_2');
checkBox2.checked = false;
checkBox2.onchange = function () {
elem2.style.display = this.checked ? 'block' : 'none';
};
checkBox2.onchange();
var elem3 = document.getElementById('div_product_3'),
checkBox3 = document.getElementById('product_3');
checkBox3.checked = false;
checkBox3.onchange = function () {
elem3.style.display = this.checked ? 'block' : 'none';
};
checkBox3.onchange();
HTML
<input type="checkbox" name="product_1" id="product_1" />
<label>Product 1</label><br>
<div id="div_product_1">
<input type="number" name="quantity_1" id="quantity_1" />
</div>
<input type="checkbox" name="product_2" id="product_2" />
<label>Product 2</label><br>
<div id="div_product_2">
<input type="number" name="quantity_2" id="quantity_2" />
</div>
<input type="checkbox" name="product_3" id="product_3" />
<label>Product 3</label><br>
<div id="div_product_3">
<input type="number" name="quantity_3" id="quantity_3" />
</div>
As alluded to in the comments, you are reusing your elem variable. Change your code so the second and third elem are unique, i.e. this jsfiddle
You can maybe try something like this. Fiddle
This is mostly so that you don't have to copy paste the whole time.
So in a nutshell, i am adding the html controls dynamically and then hooking up the onchange event on the checkboxes
HTML
<div id="placeholder"></div>
JS
var max_fields = 100; //maximum input boxes allowed
var $placeholder = $("#placeholder");
// Add html controls
for (var i = 0; i < max_fields; i++) {
$placeholder.append("<input type='checkbox' name='product_" + i + "' id='product_" + i + "'/>")
.append("<label>Product " + i + "</label")
.append("<div id='div_product_" + i + "'></div>");
var $divProduct = $("#div_product_" + i);
$divProduct.append("<input type='number' name='quantity_" + i + "' id='quantity_" + i + "' class='hide' />");
}
// wire the onclick events
$('[id*="product_"]').change(function () {
console.log($(this));
var splitId = $(this).attr("id").split("_")[1]
console.log({
id: splitId,
control: $("#quantity_" + splitId)
})
$("#quantity_" + splitId).toggle()
});
IMHO, loops should do. Also, use class instead of id on your HTML elements.
Snippet:
var numProducts=10;
var classNameProduct='product';
var classNameContainerProduct='div_product';
var classNameQuantity='quantity';
var mainContainer=document.body;
function generateMarkup(){
for(var i=0; i<numProducts; i+=1){
mainContainer.insertAdjacentHTML('beforeend','<input type="checkbox" name="'+classNameProduct+'" class="'+classNameProduct+'"/><label>Product '+i+'</label><br>');
mainContainer.insertAdjacentHTML('beforeend','<div class="'+classNameContainerProduct+'"><input type="number" name="'+classNameQuantity+'" class="'+classNameQuantity+'"/></div>');
}
}
function initCheckboxes(){
var checkboxes=document.querySelectorAll('.'+classNameProduct),containerProducts=document.querySelectorAll('.'+classNameContainerProduct);
for(var i=0; i<numProducts; i+=1){
checkboxes[i].checked=false;
containerProducts[i].style.display='none';
(function(index){
checkboxes[index].onchange=function(){ containerProducts[index].style.display=this.checked?'block':'none'; }
}(i));
}
}
generateMarkup();
initCheckboxes();
Hope this helps.
Related
I try to create array with keys and values by using the jQuery .map().
When I use my code I have a problem with formatting:
["name1:1", "name2:1", "name3:0"]
I need:
['name1':1,'name2':1,'name3':0]
I spend a few hours to make it work, but I don't know what is wrong.
HTML
<div class="inputs-container">
<input id="name1" name="name1" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name2" name="name2" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name3" name="name3" type="checkbox" class="multicheckbox-item" value="0">
</div>
JS
var inputsContainer = $('.inputs-container');
var inputValues = inputsContainer.find( 'input.multicheckbox-item' ).map( function() {
var name = $(this).attr('name');
var active = 0;
if( $(this).prop( 'checked' ) ){
var active = 1;
}
return name + ':' + active;
}).get();
console.log( inputValues );
You'll want an object and .each (or .forEach in native array terms).
var inputsContainer = $('.inputs-container');
var inputValues = {};
var inputValues = inputsContainer.find('input.multicheckbox-item').each( function() {
inputValues[$(this).attr('name')] = ($(this).prop('checked') ? 1 : 0);
});
console.log(inputValues);
Try This
var inputsContainer = $('.inputs-container');
var inputValues_key = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var name = $(this).attr('name');
return name;
}).get();
var inputValues_value = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var active = $(this).prop('checked')? 1 : 0;
return active;
}).get();
var inputValues = [], length = Math.min(inputValues_key.length, inputValues_value.length);
for(var i = 0; i < length; i++) {
inputValues.push([inputValues_key[i], inputValues_value[i]]);
}
console.log( inputValues );
I'm trying to create a variable based on the id & name of fields with a specific class. But I'm having some trouble as my JS is a bit rusty thanks to years of jQuery.
Bellow Is my code and here is the js fiddle for it.
So first off I'm checking for a click then if the class invalid exists then run a loop to find the name attribute & ID attribute of each element that has the class invalid.
That then adds it to an array and I print the array.
Simple enough but it doesn't seem to be playing ball. I'm blaming years of using jQuery on this because I should be able to pop out something as simple as a loop in JS no problem. But I'm at a loss and can't seem to find an error as to why I don't get the print to the console log.
document.getElementById("submiter").onclick = function() {
errorLoop();
};
function errorLoop() {
var errClass = element.classList.contains("invalid"),
runner = document.document.getElementsByClassName("invalid"),
dataL = [];
if (errClass) {
for (var i = 0; i < runner.length; i++) {
var errName = runner.getAttribute("name"),
errId = runner.getAttribute("id");
dataL.push("Name: " + errName + " - ID: " + errId +", ");
} //End for
dataL.toString();
console.debug(dataL);
dataLayer.push({
"validationError": "datal"
});
} //End if
} //End errorLoop
<input type="radio" id="tiMs" name="ti" value="Ms" tabindex="16" class="invalid">
<input type="radio" id="tiMiss" name="ti" value="Miss" tabindex="17" class="invalid">
<input type="radio" id="tiMiss" name="hol" value="Miss" tabindex="17" class="invalid">
<a href="#" id="submiter">
<strong>clickit</strong>
</a>
Changed code according to your requirement
function foo() {
errorLoop();
}
function errorLoop() {
var runner = document.getElementsByClassName("invalid"), dataL = [];
if (runner) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"), errId = runner[i]
.getAttribute("id");
dataL.push("Name: " + errName + " - ID: " + errId);
} //End for
dataL.toString();
console.log(dataL)
console.debug(dataL);
} //End if
} //End errorLoop
<input type="radio" id="tiMs" name="ti" value="Ms" tabindex="16"
class="invalid">
<input type="radio" id="tiMiss" name="ti" value="Miss" tabindex="17"
class="invalid">
<input type="radio" id="tiMiss" name="hol" value="Miss" tabindex="17"
class="invalid">
<a href="#" id="submiter" onclick="foo()"> <strong>clickit</strong>
</a>
You may try below changes:
function errorLoop() {
var errClass = element.classList.contains("invalid"),
runner = document.getElementsByClassName("invalid"), // removed document
dataL = [];
if (errClass) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"), //used index
errId = runner[i].getAttribute("id");
//....
} //End for
}
//....
}
Try this will may help you
$(document).ready(function(){
var arrNumber = new Array();
$('#submiter').on('click',function(){
$('input[type=radio]:checked').each(function(){
if($(this).attr('class')=='invalid'){
arrNumber.push($(this).attr('id')+' => '+$(this).attr('name'));
}
});
console.log(arrNumber);
});
});
This is my code in html and java script. I coded same things thrice, I want to do it once... what to do...............
<input type="text" name="option1" id="option1" onblur="calc_amt(1);">
<input type="text" name="price1" id="price1" onblur="calc_amt(1);">
<input type="text" name="amount1" id="amount1" readonly>
<input type="text" name="option2" id="option2" onblur="calc_amt(2);">
<input type="text" name="price2" id="price2" onblur="calc_amt(2);">
<input type="text" name="amount2" id="amount2" readonly>
<input type="text" name="option3" id="option3" onblur="calc_amt(3);">
<input type="text" name="price3" id="price3" onblur="calc_amt(3);">
<input type="text" name="amount3" id="amount3" readonly>
<script>
function calc_amt(val){
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
....
document.getElementById("amount1").value=amoun1 ;
}
if(val==2){
var option2 = document.getElementById("option2").value;
var pri2 = document.getElementById("price2").value;
...
document.getElementById("amount2").value=amoun2;
}
if(val==3){
var option3 = document.getElementById("option3").value;
var pri3 = document.getElementById("price3").value;
....
document.getElementById("amount3").value=amoun3;
}
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
how do solve it by coding only once... I am beginner please help me.... any other ideas to solve this.. i need a solution like inheritance.
You can further reduce above script like this. Your amoun is unclear for though. However you can reduce the code like this. This is just an idea and make sure you match the variables with correct statement.
<script>
function calc_amt(val){
var option1 = document.getElementById("option"+val).value;
var pri1 = document.getElementById("price"+val).value;
....
document.getElementById("amount"+val).value=""+amount+val ;
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
Replace:
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
document.getElementById("amount1").value=amoun1 ;
}
with:
var amoun = document.getElementById("amount" + val).value;
var option = document.getElementById("option" + val).value;
var pri = document.getElementById("price" + val).value;
document.getElementById("amount" + val).value=amoun;
TRY...
Remove all inline handler and use blur handler like in demo
$("input[type=text]").on("blur", function () {
var id = this.id;
var last = id.charAt(id.length - 1); // get last id string value
var optionValue = $("#option" + last).val();
var priceValue = $("#price" + last).val();
var option = isNaN(optionValue) ? 0 : +optionValue; // check is nan
var price = isNaN(priceValue) ? 0 : +priceValue;
$("#amount" + last).val(option * price); // display multiply value
$("#amount").text($("input[type=text][id^=amount]").map(function () { // collect all amount1,2,3 values
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) { // add total value
return a + b;
}));
});
DEMO
OPTIMIZED CODE
$("input[type=text]:not([readonly])").on("blur", function () {
var obj = $();
obj = obj.add($(this)).add($(this).prevUntil('[readonly]')).add($(this).nextUntil('[readonly]'));
$(this).nextAll('[readonly]').first().val($.map(obj, function (val, i) {
return parseInt(val.value, 10) || 0;
}).reduce(function (a, b) {
return a * b
}, 1));
$("#amount").text($("input[type=text][id^=amount]").map(function () {
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) {
return a + b;
}));
});
DEMO
I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle
Hello I'm new to JavaScript and trying to get a radio button to be registered on variable and then have that variable return another var but it just keeps being returned undefined. If I'm just doing something overtly wrong please tell me.
The radio buttons
Fighter:<input type="radio" id="fig" value="1"/>
Cleric:<input type="radio" id="cleric" value="2"/>
Sorcerer:<input type="radio" id="wiz" value="3"/>
my js
var lvl
var bab
if (document.getElementById('fig').checked) {
var cass = document.getElementById('fig').value;
if (cass == 1){
bab = 1;
}
else if (cass == 2){
bab = 2;
}
else{
bab = 3;
}
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.value = bab;
}
And my final place its supposed to be submitting.
<input id="txtOutput">
</input>
Add change event listener for all radio inputs and on change of the input, set the value of the textbox.
Document.querySelectorAll Returns a list of the elements within the document that match the specified group of selectors.
Try this:
var elems = document.querySelectorAll('[name="name"]');
Array.prototype.forEach.call(elems, function(elem) {
elem.addEventListener('change', function() {
document.getElementById("txtOutput").value = this.value;
});
});
Fighter:
<input type="radio" id="fig" value="1" name='name' />Cleric:
<input type="radio" id="cleric" value="2" name='name' />Sorcerer:
<input type="radio" id="wiz" value="3" name='name' />
<br>
<input id="txtOutput">
I think this will give you clarity.
var lvl = "";
var bab = "";
function getValues() {
if (document.getElementById('fig').checked) {
bab = "1 : " + document.getElementById('fig').value + "\n";
}
if (document.getElementById('cleric').checked) {
bab += "2 : " + document.getElementById('cleric').value + "\n";
}
if((document.getElementById('wiz').checked)){
bab += "3 : " + document.getElementById('wiz').value;
}
show();
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.innerHTML = bab;
}
/* or you can call it when you click on it */
function consoleIt(obj) {
console.log(obj.id + " : " + obj.value);
}
Fighter : <input type="radio" onclick="consoleIt(this);" id="fig" value="1"/>
Cleric : <input type="radio" onclick="consoleIt(this);" id="cleric" value="2"/>
Sorcerer : <input type="radio" onclick="consoleIt(this);" id="wiz" value="3"/>
<button onclick="getValues();">Get Radio Data</button>
<textarea id="txtOutput"> </textarea>