Take a look at this:
<div id="main">
<div id="a">
<input value="1" />
<input value="2" />
<input value="3" />
</div>
<div id="b">
<input value="4" />
<input value="5" />
</div>
</div>
I need to get each input value inside div#a and each input value in div#b and build a matrix/mixing of those values, taking the same example as before, this is what the code should return:
<div id="mixed">
<input value="1" /><input value="4" />
<input value="1" /><input value="5" />
<input value="2" /><input value="4" />
<input value="2" /><input value="5" />
<input value="3" /><input value="4" />
<input value="3" /><input value="5" />
</div>
I have tried to move inside div#main using this code:
$("#main div").each(function() {
var that = $(this);
console.log("that.attr('id')");
});
But console.log() never logs something so I must doing something wrong. This is a advanced topic for me and need some help, any?
UPDATE
At this point I have this maded:
$("#choices div").each(function() {
var that = $(this);
that.each(function() {
var thati = $(this);
console.log(thati);
});
});
And I think in the second .each() is where I can get the input values and try to build the matrix
Should help:
var arr = [];
$('#a input').each(function () {
var that = $(this);
$('#b input').each(function () {
arr.push(that.val());
arr.push($(this).val());
});
});
Then go through the array and dynamically generate the HTML. You can treat this like a matrix by stepping every 2 values.
var a = $('#a input');
var b = $('#b input');
var html = '';
a.each(function () {
var first = this;
b.each(function () {
html += '<div>' + first.outerHTML + this.outerHTML + '</div>'
});
});
$('#mix').html(html);
jsFiddle here
update: code for what's asked for in comments.
var divs = $('#main > div');
var html = '';
divs.each(function (index) {
var divsLength = divs.length,
inputs = $('input', divs[index]),
inputsLength = inputs.length;
for (var i = 0; i < divsLength; i++) {
if (i === index) {
continue;
}
for (var j = 0; j < inputsLength; j++) {
$('input', divs[i]).each(function () {
html += inputs[j].outerHTML + this.outerHTML + '<br />';
});
}
}
});
$('#mix').html(html);
Related
Here’s the problem. I need to append a section after the user clicks an radio button. Then I need to append another section if the use clicks the radio button in this new, appended section. My code doesn’t works. I’m doing something wrong :( your help is appreciated!!!
<section class="input_1">
<input type="datetime-local"><br/>
<input id="add_1" type="radio" value="1" name="q1">yes
<input id="del_1" type="radio" value="0" name="q1" >no
<br />
</section>
$(document).ready(function() {
var max_fields = 2;
var x = 1;
$(document).on("click", "#add_1", function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(".input_1").append('<section class="input_2">-.-.-<br/><input type="datetime-local"><br />
<input type="datetime-local"><br/>
<input id="add_2" type="radio" value="1" name="q2">yes
<input id="del_2" type="radio" value="0" name="q2" >no
</section>');
})
}
});
});
$(".input_1").on("click", "#del_1", function(e) {
e.preventDefault();
$(this).parent('section').remove();
x--;
})
});
//level 2
$(document).ready(function() {
var max_fields_2 = 2;
var x = 1;
$(document).on('click', '.add_2', function(e) {
e.preventDefault();
var wrapper_2 = $(".input_2");
if (x < max_fields_2) {
x++;
$(wrapper_2).append('<section>-.-.-<br/><input type="datetime-local">Remove<br /> <button class="add_3">return 2</button> </section>');
$(wrapper_2).on("click", ".del_2", function(e) {
e.preventDefault();
$(this).parent('section').remove();
x--;
})
}
});
});
edit Here is an alternative version of the code according to the solution offered by vlk
<input type="datetime-local"><br/>
<input id="add_1" type="radio" value="1" name="q1" onclick="appendNewDiv()" ><label for="add_1">yes</label>
<input id="del_1" type="radio" value="0" name="q1" onclick="removeDiv($(this))"> <label for="add_del">no</label>
<br />
<div class="container"></div>
JavaScript
var newDiv
function appendNewDiv(){
newDiv = '<div><p>This is a new div</p>';
newDiv += '<label><input onclick="appendNewDiv()" '
newDiv += 'type="radio">Add Another Div</label>'
newDiv += '<label><input onclick="removeDiv($(this))" '
newDiv += 'type="radio">Remove Div</label></div>'
$('.container').append(newDiv);
}
function removeDiv(radio){
radio.closest('div').remove()
}
Try with something of very simple like this.
Use inline events call
onclick="yourFunction()"
on appended div to make it smarter and with less code.
Create a variable for the new div like this
var newDiv = '<div>Hello</div>';
var newDiv;
function appendNewDiv(){
newDiv = '<div><p>This is a new div</p>';
newDiv += '<label><input onclick="appendNewDiv()" ';
newDiv += 'type="radio">Add Another Div</label></div>';
$('.container').append(newDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input onclick="appendNewDiv()" id="radio1" type="radio">
Add Div
<label>
<div class="container"></div>
I try to change each hidden input value if checkbox is checked using jquery
I need to using for loop because html input field is generate by php loop from db too. so here is generated html code look like :
Html :
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="" type="hidden">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="" type="hidden">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="" type="hidden">
Jquery :
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = '#gift' + i;
var val = '#gift-true' + i;
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
but this code didn't work.
P.S :
code to generate html input is look like this :
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' id='gift$i' name='exm$i' value='1'> <br>
<input type='hidden' id='gift-true$i' value=''></td> <br><br>";
}
You can do this by using next() function as all the inputs are next to the checkbox. please replace var tot = 3; with var tot = <?php echo $tot; ?>; and type="text" with type="hidden"
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Changes this two value in your code
var chk = $('#gift' + i).val();
var val = $('#gift-true' + i).val();
This is what u want i guess
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Try this
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = $('#gift' + i);
var val = $('#gift-true' + i);
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
You need to get object instead of string right now you are getting a string which is '#gift' + i. Wrap it inside $('#gift' + i) to get the object.
Only relevant input should be set on change of a checkbox. You should not loop again for each input on change event.
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
// no need for another loop as you should target only relevant input field
$('input#gift-true' + i).val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
Yo do not need loop here. Just change the value of the next input.
$('input[type="checkbox"]').change(function(){
var $hidden = $(this).next('input[type="hidden"]');
if ($hidden.length) {
var checked = $(this).is(':checked');
if (checked) {
$hidden.val('yes');
} else {
$hidden.val('no');
}
}
});
//call function for every checkbox which are already on page
$('input[type="checkbox"]').change();
This code will work for every checkbox on the page. To avoid this just use stronger selector: $('.some-class input[type="checkbox"]')
My answer, similar to a few others, also eliminates the for loop.
jQuery(function ($) {
// do this if you do not know the state of the generated checkbox
$("input[type='checkbox']").each(function () {
$(this).next().val($(this).prop("checked") ? "yes" : "no");
});
// then this for your event handler
$("input[type='checkbox']").on("change", function (e) {
$(e.target).next().val($(e.target).prop("checked")?"yes":"no");
})
});
Change you id to class
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' class='gift' name='exm$i' value='1'> <br>
<input type='hidden' name='gift-exm$i' class='gift-true' value=''></td> <br><br>";
}
refactor your code as follows
$('.gift').change(function(e) {//remove any loops /keep the change event
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");//select the hidden input using next()
});
ps: don't forget to add a name to the hidden input
$('.gift').change(function(e) {
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
I have a list of checkboxes, and I need to disable my submit button if none of them are checked, and enable it as soon as at least one gets checked. I see lots of advice for doing this with just a single checkbox, but I'm hung up on getting it to work with multiple checkboxes. I want to use javascript for this project, even though I know there are a bunch of answers for jquery. Here's what I've got - it works for the first checkbox, but not the second.
HTML:
<input type="checkbox" id="checkme"/> Option1<br>
<input type="checkbox" id="checkme"/> Option2<br>
<input type="checkbox" id="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
I'd group your inputs in a container and watch that for events using addEventListener. Then loop through the checkboxes, checking their status. Finally set the button to disabled unless our criteria is met.
var checks = document.getElementsByName('checkme');
var checkBoxList = document.getElementById('checkBoxList');
var sendbtn = document.getElementById('sendNewSms');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
<div id="checkBoxList">
<input type="checkbox" name="checkme"/> Option1<br>
<input type="checkbox" name="checkme"/> Option2<br>
<input type="checkbox" name="checkme"/> Option3<br>
</div>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
html
<input type="checkbox" class="checkme"/> Option1<br>
<input type="checkbox" class="checkme"/> Option2<br>
<input type="checkbox" class="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
js
var checkerArr = document.getElementsByClassName('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
for (var i = 0; i < checkerArr.length; i++) {
checkerArr[i].onchange = function() {
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
}
I guess this code will help you
window.onload=function(){
var checkboxes = document.getElementsByClassName('checkbox')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkbox"/> Option1<br>
<input type="checkbox" id="check2" class="checkbox"/> Option2<br>
<input type="checkbox" id="check3" class="checkbox"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Few suggestions
1.Always id should be unique. HTML does not show any error, if you give multiple objects with the same id but when you try to get it by document.getelementbyid it always return the first one,because getelementbyid returns a single element
when there is such requirement, you should consider having a classname or searching through the element name because getelementsbyclassname/tag returns an array
Here in the markup i have added an extra class to query using getelementsbyclassname
To avoid adding extra class, you can also consider doing it by document.querySelectorAll
check the following snippet
window.onload=function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" /> Option1<br>
<input type="checkbox" id="check2" /> Option2<br>
<input type="checkbox" id="check3" /> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Hope this helps
Something like this would do. I'm sure you can do it with less code, but I am still a JavaScript beginner. :)
HTML
<input type="checkbox" class="checkme" data-id="checkMe1"/> Option1<br>
<input type="checkbox" class="checkme" data-id="checkMe2"/> Option2<br>
<input type="checkbox" class="checkme" data-id="checkMe3"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
JavaScript
//keep the checkbox states, to reduce access to the DOM
var buttonStatus = {
checkMe1: false,
checkMe2: false,
checkMe1: false
};
//get the handles to the elements
var sendbtn = document.getElementById('sendNewSms');
var checkBoxes = document.querySelectorAll('.checkme');
//add event listeners
for(var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('change', function() {
buttonStatus[this.getAttribute('data-id')] = this.checked;
updateSendButton();
});
}
//check if the button needs to be enabled or disabled,
//depending on the state of other checkboxes
function updateSendButton() {
//check through all the keys in the buttonStatus object
for (var key in buttonStatus) {
if (buttonStatus.hasOwnProperty(key)) {
if (buttonStatus[key] === true) {
//if at least one of the checkboxes are checked
//enable the sendbtn
sendbtn.disabled = false;
return;
}
}
}
//disable the sendbtn otherwise
sendbtn.disabled = true;
}
var check_opt = document.getElementsByClassName('checkit');
console.log(check_opt);
var btn = document.getElementById('sendNewSms');
function detect() {
btn.disabled = true;
for (var index = 0; index < check_opt.length; ++index) {
console.log(index);
if (check_opt[index].checked == true) {
console.log(btn);
btn.disabled = false;
}
}
}
window.onload = function() {
for (var i = 0; i < check_opt.length; i++) {
check_opt[i].addEventListener('click', detect)
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkit" />Option1
<br>
<input type="checkbox" id="check2" class="checkit" />Option2
<br>
<input type="checkbox" id="check3" class="checkit" />Option3
<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="true" id="sendNewSms" value=" Send " />
This is my java script
<script>
$(document).ready(function () {
$('#btnSubmit').on('click', function (e) {
var cnt = $("input[name='technologies']:checked").length;
var cnt1 = $("input[name='technologies']:checked").val();
alert(cnt1);
if (cnt < 3) {
for (i = 0; i < $("input[name='technologies']:checked").length; i++) {
var cnt2 = cnt1.val(i);
alert(cnt2)
}
alert(cnt);
e.preventDefault();
}
else
alert('Well Done!!!!');
});
});
</script>
My html code
<input type="checkbox" name="technologies" value="JavaScript" />JavaScript <br />
<input type="checkbox" name="technologies" value="Prototype" /> Prototype<br />
<input type="checkbox" name="technologies" value="Dojo" /> Dojo<br />
<input type="checkbox" name="technologies" value="Mootools" /> Mootools <br /></div></td></tr></table>
I need the values of checked in forloop statement. Unable to get the checked values, i am getting only one checked value
You're confused as to what returns an array and what doesn't.
var elms = $("input[name='technologies']:checked")
for (i = 0; i < elms.length; i++) {
var cnt2 = elms[i].val();
alert(cnt2)
}
elms is an array, whose elements can by accessed by index.
Hi here is the codes bellow, I've tried many things but I couldnt get value of selected radio button.As you can see I need to get that value for diffrent situations.
<div style="display: inline-block">
<div>
Log Out<span> Welcome </span>YS User 1 noName </div>
<br />
<br />
<br />
<br />
<input type="button" onclick="submitCreate();" value="New Survey" /><br />
<input type="button" onclick="submitEdit();" value="Edit Survey" /><br />
<input type="button" onclick="submitDelete();" value="Delete Survey" /><br />
<input type="button" onclick="submitPreview();" value="Preview Survey" />
</div>
<div style="display: inline-block">
<div>
<table class="MyTable"><thead><tr class="columnHead"><th scope="col"></th><th scope="col">CreatedBy</th><th scope="col">Created Date</th><th scope="col">Is Running</th></tr></thead><tbody><tr><td> <input name="selected" id="1"
type="radio" value="1" /></td><td>1</td><td>12/12/2011 3:43:57 PM</td><td>False</td></tr><tr class="altRow"><td> <input name="selected" id="2"
type="radio" value="2" /></td><td>1</td><td>12/13/2011 4:42:37 PM</td><td>False</td></tr><tr><td> <input name="selected" id="3"
type="radio" value="3" /></td><td>1</td><td>12/13/2011 6:27:38 PM</td><td>False</td></tr></tbody></table>
</div>
</div>
</body>
</html>
<script type="text/javascript">
// var value = $$('input[name=selected]:checked')[0].get('value');
// var selectFoo;
// $$('input[name=selected]').each(function (el) {
// if (el.checked == true) {
// selectFoo = el.value;
// }
// });
function getCheckedValue(radioObj) {
if (!radioObj)
return "";
var radioLength = radioObj.length;
if (radioLength == undefined)
if (radioObj.checked)
return radioObj.value;
else
return "";
for (var i = 0; i < radioLength; i++) {
if (radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
};
function submitCreate() {
var adress = "/User/CreateSurvey/";
document.location = adress;
};
function submitEdit() {
var adress = "/Den/Index/" + getCheckedValue('selected');
document.location = adress;
};
function submitDelete() {
var adress = "/User/DeleteSurvey/" + getCheckedValue('selected');
document.location = adress;
};
function submitPreview() {
var adress = "/User/PreviewSurvey/" + getCheckedValue('selected');
document.location = adress;
};
</script>
You can use document.getElementsByName(<button_name>) or document.getElementsByTagName("input") to get an array of input elements. Loop through those elements to check which is checked.
Here is an example of how to get the value of the checked button from a set of radio buttons with the name "selected":
<html>
<head>
<script type="text/javascript">
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_radio_value();
alert("selected input is: " + id);
}
</script>
</head>
<body>
<form onsubmit="onSubmit();">
<input name="selected" value="1" type="radio"/>1<br/>
<input name="selected" value="2" type="radio"/>2<br/>
<input name="selected" value="3" type="radio"/>3<br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
I choose let number of code for a required function. The one worked for me is given below from api.jquery.com. Hope this helps others.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2