Uncheck Selected checkbox on button click - javascript

I have already tried all the given methods to uncheck checkbox in jquery, please find my below code.
$('#btnDeleteEnterpriseID').click(function () {
$('#chkbox').prop('checked', false);
$('#chkbox').removeAttr('checked');
$('#chkbox').checked = false;
$('#chkbox').attr('checked', false);
$('#chkbox input:checkbox').attr('checked', false);
$('#chkbox input[type=checkbox]').removeAttr('checked');
});
Have tried with all methods that I could get till now.
Below is the code for my checkbox and button.
#helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" value="#s"class="edit-mode" />#s <br />}
}
Here, #DisplayMultiline is helper class which I used in Web Grid column as shown below,
grid.Column(columnName: "EnterpriseID",
format:#<text><span class="display-mode">
<label id="EnterpriseId" ></label>
</span>#DisplayMultiLine(#item.EnterpriseId)</text>),
And I want this checkbox to get unchecked on click event of delete button, code for it given below.
<button type="button" id="btnDeleteEnterpriseID"
value="Delete" class="cancel-user edit-mode" onclick="DeleteEnterpriseID()">Delete</button>
I am not getting my mistake, kindly assist.
Kindly note, I have not used all those possibilities together, I just wanted to tell that I have used almost all methods and have tried them one by one.

You are generating duplicate identifiers in your foreach:
#helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" value="#s"class="edit-mode" />#s <br />}
}
When you have multiple objects with the same id, jquery is having trouble to distinguish which one of them you aim at.
Jquery will either work only on the first one it will match or won't work at all. Find a way to distinguish between every check box.
for example:
#helper DisplayMultiLine(string str)
int i = 0;
{ foreach (string s in str.Split(new char[] { ',' }))
{ <input type="checkbox" id="chkbox" + i value="#s"class="edit-mode" />#s
}
i++;
}

Related

How to create a clickable list with multiple values in an element?

I am trying to create a list of names an user could chose from to select a object with multiple hidden values. I work with a PHP backend.
The code I wrote works but I think it is probably not the right way to approach the problem and could be written alot better, but I can't seem to find a better way.
Right now I print a <div> for every object which are clients in my case. Within the div I have four checkboxes that are hidden, which I check and uncheck on the background with a javascript function. The values of those checkboxes is what I need in javascript for an API call after the user choses the client.
I select and deselect the with a javascript function.
foreach($clients as $client) {
echo '<div class="'.$client->name.'-'.$client->id.' client-style" name="'.$client->name.'">
<input type="checkbox" class="'.$client->id.'" name="client_id" value="'.$client->id.'">
<input type="checkbox" class="'.$client->id.'" name="client_fb" value="'.$client->facebook.'">
<input type="checkbox" class="'.$client->id.'" name="client_insta" value="'.$client->instagram.'">
<input type="checkbox" " class="'.$client->id.'" name="client_wb" value="'.$client->website.'"></div>';
}
For every element I create an on click event handler
for (var i = 0; i < clientList.length; i++) {
const {name, id} = clientList[i];
$(`.${name}-${id}`).on('click', function() {
selectClientFromList({name, id});
});
}
I am trying to get a list of clickable "names". When a "name" is clicked, you want to get the "name" but also "id", "facebook", "instagram", "website".
Might be useful to use the <select> tag with multiple values like this but I don't want a dropdown. I need a scrollable list, because I also have use searchbar for this list.
With a lot of clients the html would grow fast. How do I clean my php code and keep the information about a client that the user selected?
Thanks in advance!
A good approach can be to use a hidden input. Give your div a class and then
foreach($clients as $client) {
echo '
<div class="'. $client->name.'-'.$client->id.' client-style" name="'.$client->name.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_id" value="'.$client->id.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_fb" value="'.$client->facebook.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_insta" value="'.$client->instagram.'">
<input type="hidden" class="aclass '.$client->id.'" name="client_wb" value="'.$client->website.'"></div>';
}
And then instead of creating a click handler everytime. One works too.
$(`.aclass`).on('click', function() {
let type = $(this).attr('name'); // client_id or client_fb
let client_id = $(this).attr('class').replace("aclass",""); // $client->id's value is here
let value = $(this).val(); // credentials
});

Checking or unchecking a checkbox based on value in a group with Javascript

I am really new to Javascript and know absolutely nothing about JQuery, so I apologize now for my newbie status.
I have an array of checkboxes (up to 18) that have the same name and class (can't change that fact):
<input type="checkbox" name="elective_id[]" value="112" class="elective_id">
<input type="checkbox" name="elective_id[]" value="128" class="elective_id">
<input type="checkbox" name="elective_id[]" value="135" class="elective_id">
<input type="checkbox" name="elective_id[]" value="322" class="elective_id" onClick="checkSister(322);">
<input type="checkbox" name="elective_id[]" value="323" class="elective_id" onClick="checkSister(323);">
Within that array will be 3 pairs of checkboxes that need their counterpart checked/unchecked when their pair is checked/unchecked. The three pairs are 320,321 & 322,323 & 345,346.
If checkbox with value 322 was selected, how can I automatically select the pair?
function checkSister(brother) {
if (brother=="322") {
document.getElementById("322").checked = true;
document.getElementById("323").checked = true;
} else if (brother=="322") {
document.getElementById("322").checked = true;
document.getElementById("323").checked = true;
}
}
I know that is not right, but haven't figured out how to get the right variable selected, let alone deselected.
Any help you can provide would greatly be appreciated,
Jim
You can do it easily without jquery using querySelectorAll
document.querySelectorAll("input[type='checkbox'][value='112']")[0].checked=true;
or you can query by name and value like this:
document.querySelectorAll("input[name='elective_id[]'][value='112']")[0].checked=false;
To convert that vanilla JavaScript to jQuery,
function checkSister(brother) {
if (brother=="322") {
$("#322").prop("checked") = true;
$("#323").prop("checked") = true;
} else if (brother=="322") {
$("#322").prop("checked") = true;
$("#323").prop("checked") = true;
}
}

Why this javascript not enabling text boxes using check box?

Again in problem
Actually I have following jsp code in which I have few text boxes which I have made disabled by using property disabled="disabled".
Now problem is each record that I will get from database in each text box using iterator which iterates values added from databse in arraylist.If database return more than one record then using that check box I can enable textboxes but if databse resultset return only one record then I am unable to enable textboxes and throws following ERROR:
Message: 'document.f1.chk' is null or not an object
Line: 26
Char: 10
Code: 0
<script type="text/javascript">
function enable()
{
for(i=0;i<document.preapp.chk.length;i++)
{
if(document.preapp.chk[i].checked==true)
{
document.preapp.id[i].disabled=false;
document.preapp.vname[i].disabled=false;
document.preapp.comp[i].disabled=false;
document.preapp.cont[i].disabled=false;
document.preapp.wtm[i].disabled=false;
document.preapp.intime[i].disabled=false;
}
else
if(document.preapp.chk[i].checked==false)
{
document.preapp.id[i].disabled=true;
document.preapp.vname[i].disabled=true;
document.preapp.comp[i].disabled=true;
document.preapp.cont[i].disabled=true;
document.preapp.wtm[i].disabled=true;
document.preapp.intime[i].disabled=true;
}
}
}
</script>
<CENTER>Back to Search</CENTER>
<form method="post" action="" name="preapp">
<table border="1" align="center" width="100%">
<%
Iterator itr;
try
{
ArrayList al=(ArrayList)request.getAttribute("sq");
int i=0;
for(itr=al.iterator();itr.hasNext();)
{
i=i+1;
%>
<tr>
<td></td><td><input type="checkbox" name="chk" onclick="enable(this)" ></td></tr></tr>
<tr><td>Id</td><td><input type="text" name="id" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Visitor Name</td><td><input type="text" name="vname" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Comapny</td><td><input type="text" name="comp" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Contact</td><td><input type="text" name="cont" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Meeting Scheduled With</td><td><input type="text" name="wtm" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Entry Made On</td><td><input type="text" name="intime" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td></td>
</tr>
<tr>
</tr>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
%>
How Do solve this problem? please help me out!
It works like charm, except in the case you have only one TR block.
In that case, the .chk has no "length" attribute!
You should consider that case separately:
function enable()
{
if(document.preapp.chk.length == null)
{
disabledState = !document.preapp.chk.checked
document.preapp.id.disabled=disabledState;
document.preapp.vname.disabled=disabledState;
document.preapp.comp.disabled=disabledState;
document.preapp.cont.disabled=disabledState;
document.preapp.wtm.disabled=disabledState;
document.preapp.intime.disabled=disabledState;
} else {
for(i=0;i<document.preapp.chk.length;i++)
{
disabledState = !document.preapp.chk[i].checked
document.preapp.id[i].disabled=disabledState;
document.preapp.vname[i].disabled=disabledState;
document.preapp.comp[i].disabled=disabledState;
document.preapp.cont[i].disabled=disabledState;
document.preapp.wtm[i].disabled=disabledState;
document.preapp.intime[i].disabled=disabledState;
}
}
}
a couple of suggesions: instead of setting the properties of elements to true or false, try using the setAttribute and removeAttribute methods:
document.preapp.id[i].disabled=true;
//replace with:
document.preapp.id[i].setAttribute('disabled','disabled');
//to enable:
document.preapp.id[i].removeAttribute('disabled');
The way you're doing things works fine 99.9% of the time. I haven't seen the above code fail, though (I have had issues with the true/false approach).
Next: the error message you post, contains very useful information: check line 26 of your original code. 'document.f1.chk' is nowhere to be found in your snippet, so I can't check for typo's or other possible problems in your code there.
You're passing the element to the enable function, too. Why then, are you looping through all elements, checking all elems on the page?
function enable(elem)
{
var i = document.preapp.indexOf(elem);//
if (elem.checked === true)
{
document.preapp.id[i].removeAttribute('disabled');
//...
}
//functions have properties, exploit them:
if (typeof enable.previous === 'undefined' || enable.previous === i)
{
enable.previous = i;
return true;
}
document.preapp.id[enable.previous].setAttribute('disabled','disabled');
//...
enable.previous = i;
}
The last section of the enable function stores the index of the checkbox that was just clicked, so that when the enable function has been clicked before, there's no need to loop through all elements again: enable.previous holds the index of the checkbox that was clicked last time.
Lastly: there are no opening or closing bracket for the else block, and there is an extra line of whitespace. Else works fine without brackets, but only branches one line. In your code, this line is blank: either remove the else, or add brackets.
PS: Perhaps a fiddle would help to get a clear view of the situation?
As Teejay pointed out, in case of unique names, the elements are referenced directly, instead of a nodesList being passed.

JS / JQuery - Check All Checkboxes

I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.

Use javascript comma separated variable to repopulate a forms checkbox values when page loads

I have a jquery variable that is storing a comma separated list of id names. I need help writing something in jquery that separates that variable and uses those values to populate a forms checkbox values when the page loads.
so my jquery variable is $storedFormValues that is a comma separated list of values "checkbox1, checkbox, etc."
and my form
<form name="formname" id="formid">
<input type='checkbox' class='catcheck' id='checkbox1' value='checkbox1' name='catselect' />Checkbox 1
<input type='checkbox' class='catcheck' id='checkbox2' value='checkbox2' name='catselect' />Checkbox 2
<input type="submit" name="submit" value="Submit" />
</form>
Any help would be greatly appreciated!
This should do it:
var $storedFormValues = "checkbox3,checkbox5";
$(function() {
$.each($storedFormValues.split(","), function(intIndex, objValue) {
$("#" + objValue).attr("checked", "true");
});
})
See the fiddle: http://jsfiddle.net/xNyww/
Not jQuery, but plain JS: You can use split to separate the values in an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
I do not know what do the csv looks like. If it's only one line, e.g:
checkbox1, checkbox7, checkbox2
then use it as:
var checkboxes[] = csvString.split(",");
for (str in checkboxes) {
$("#"+str).yourActionHere();
}
If it's several lines (one per checkbox) , e.g.
checkbox1, true
checkbox2, false
then :
var checkboxes[] = csvString.split(/\r\n|\r|\n/);
for (str in checkboxes) {
var data = str.split(",");
$("#"+data[0]).yourActionHere(data[1]);
}
Live Demo
var storedFormValues = "checkbox1, checkbox3, checkbox4";
$('#formid').children('input[id^=checkbox]').each(function() {
if (storedFormValues.indexOf($(this).attr('id')) != -1) {
$(this).attr('checked', 'checked');
}
});
Note: If you plan on having more than 10 checkboxes, I recommend naming them with a leading zero (ex: checkbox01) otherwise you may run into an issue where checkbox1 matches against checkbox11.

Categories