I am creating check boxes dynamically using jquery. I want to disable unchecked check boxes as shown in the snippet,but i want to disable the check boxes only in their respective div elements and not in the other div elements which is what causing issue now.
I have written the code to disable/enable checkboxes based on their respective div tags and i have commented it as it is throwing error if enabled.
$($(".checkbox").eq(id).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Problem explanation : Here i am creating two div tags dynamically inside which check boxes are also created with same name. So if i check on checkbox in first div other checkbox gets disabled and other div tag gets created which works as expected. but if i check any option in second div tag other option in second div tag doesn't get disabled and also if i uncheck the checked option in first div tag both options get disabled in first div tag. I guess this is because all checkboxes have same names.
How can we disable checkboxes only in their respective div tags. I tried below code but didn't work
$($(".checkbox").eq(1).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Below snippet explains the problem more appropriately
Please help me.
function checkdiv(id, val) {
if ($(":checkbox[name='radio']:checked").length == 1)
$(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>
Have you tried ".find" in the jQuery API - this will only find elements within the specified selector - see the modifications to the "checkdiv" function ($('#' + id))
function checkdiv(id, val) {
if ($('#' + id).find(":checkbox[name='radio']:checked").length == 1)
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>
Related
I am stuck at this point trying to simulate an ajax search box. Take a look a very simple html markup
<div data-role="page" id="lightbox">
<div role="main" class="ui-content">
<div class="ui-field-contain">
<label for="search-input">Seach</label>
<input id="search-input" type="text" name="search" />
</div>
<div class="ui-field-contain">
<label for="results"></label>
<div id="results" data-role="controlgroup" data-input="#search-input"></div>
</div>
</div>
</div>
My intention is to add every "result" as an input radio into the controlgroup. I made it work with the following code:
var counter = 1;
$("#search-input").on("keyup", function (e) {
var $group = $("#results");
var source = ['mark', 'marcus', 'mariah', 'mary']
var value = $(this).val();
// This line is commented because of the problem
//$group.html("");
if (value && value.length > 2) {
$group.controlgroup("refresh");
$.each( source, function ( i, val ) {
var $el = $("<label for='user-" + counter + "'>" + val + "</label><input name='users' id='user-" + counter + "' value='x' type='radio'></input>");
$group.controlgroup("container").append($el);
$( $el[ 1 ] ).checkboxradio();
counter ++;
});
$group.controlgroup("refresh");
}
});
What is the problem? Well, for each keyup event I want to clear/empty the controlgroup in order to remove the appended elements from previous search. If I use $group.html(""); (see the commented code line) the incomming results are not appended. You can see live example at:
http://jsfiddle.net/manix/4rjkermc/3/
You can make use of $group.controlgroup("container").empty(); to empty your group container. see below code and jsfiddle
var counter = 1;
$("#search-input").on("keyup", function (e) {
var $group = $("#results");
var source = ['mark', 'marcus', 'mariah', 'mary']
var value = $(this).val();
// This line is commented because of the problem
//$group.html("");
$group.controlgroup("container").empty();//empty your container
if (value && value.length > 2) {
$group.controlgroup("refresh");
$.each( source, function ( i, val ) {
var $el = $("<label for='user-" + counter + "'>" + val + "</label><input name='users' id='user-" + counter + "' value='x' type='radio'></input>");
$group.controlgroup("container").append($el);
$( $el[ 1 ] ).checkboxradio();
counter ++;
});
$group.controlgroup("refresh");
}
});
JSFiddle Demo
I have this code for multi check-box
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
jQuery/JavaScript:
myArray1 = new Array(
"1","2","3","4","5","6"
);
$("#ZIBI").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
$("#ZIBI").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
$('#ZIBI').trigger('create');
how to check all or uncheck all by pressing any button ?
thanks
In this JsFiddle you'll find a method to check/uncheck all checkboxes within a given div, using a checkbox with id _main:
function checkAll(e){
e = e || event;
var from = e.target || e.srcElement
,cbs = this.querySelectorAll('input'), i=1;
if (/^_main$/i.test(from.id)){
for (;i<cbs.length;i+=1){
cbs[i].checked = from.checked;
}
} else {
var main = document.querySelector('#_main')
,j = cbs.length;
for (;i<cbs.length;i+=1){
j -= cbs[i].checked ? 0 : 1;
}
main.checked = j === cbs.length ? true : false;
}
}
Update
New elements should be added to $(".selector").controlgroup("container") not $(".selector") directly. If you add them to main div, elements won't be styled as a _controlgroup`.
You need to refresh .checkboxradio("refresh") checkbox or radio to apply jQM styles. Another point, .trigger("create") is deprecated as of jQM 1.4 and replaced with .enhanceWithin().
myArray1 = new Array(
"1", "2", "3", "4", "5", "6");
/* remove previous elements */
$("#ZIBI").controlgroup("container").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
/* add new ones to container */
$("#ZIBI").controlgroup("container").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
/* refresh controlgroup and enhance elements within */
$("#ZIBI").controlgroup().enhanceWithin();
/* check/uncheck on button click */
$("#foo").on("click", function () {
var status = $("#ZIBI [type=checkbox]").eq(0).prop("checked") ? false : true;
$("#ZIBI [type=checkbox]").prop("checked", status).checkboxradio("refresh");
});
Demo
You can try this:
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
<input type="checkbox" id="all" value="Toggle" />
jQuery:
$('#all').on('click', function() {
if(this.checked) {
$('#ZIBI').find('input[type=checkbox]').prop('checked', true);
} else {
$('#ZIBI').find('input[type=checkbox]').prop('checked', false);
}
});
Working Fiddle.
Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}
I have 2 buttons add and group. Initially group button is hidden. Add button is used for creating records.
So for example:
When 5 records are created(pressing 5 times add button). Now if user selects more than
checkbox, then the hidden group button should appear. Can any body please tell me how to do this?
Please see this fiddle
I am using bootstrap css and for hiding I do as
<input type="button" id="btn2" class="btn btn-lg btn-primary hide" value="Group">
UPDATE
Check boxes will only appear if user enters some records. Filling the form and after pressing the add button
See this FIDDLE
$(document).on('change','#mytable input:checkbox',function () {
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
});
Here's the FIDDLE
if($('#mytable input:checkbox:checked').length > 1)
$('#btn2').show();
else
$('#btn2').hide();
Add a check in the change event for the checkboxes. fiddle and example below:
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//updated using your bootstrap class to show/hide
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide');
} else {
$('#btn2').addClass('hide');
}
});
Updated to use bootstrap class as per your updated question.
Try This
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});;
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
var rowCount = $('#mytable tr').length;
if($('input:checkbox:checked').length > 1 && rowcount > 6) {
$('#btn2').removeClass('hide')
}
});
});
Updted Fiddle is : http://jsfiddle.net/4GP9c/184/
I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}