I want to update my text value when I check checkbox - javascript

I have a form, it has a checkbox , value(how many item do you want) , item(ex: pen,eraser).
My value set 0,I hope when I checked, value will turn 0 -> 1
This is my code:
<div class="container">
<table>
<thead>
<tr><th>checkbox</th><th>value</th><th>item</th></tr>
</thead>
<tbody id="myTable">
<%
String sql = "select * from send";
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
pstmt.setQueryTimeout(60);
while(rs.next()){
String name = rs.getString("name");
String c_id = rs.getString("c_id");
out.print("<tr><td>"+"<input type=checkbox name='a'id='a' value="+c_id+" onclick='testfun( this,"+c_id+")'>"+"</td>"
+ "<td><input type=text id='"+c_id+"' value=0 SIZE=5></td><td>"+name+"</td></tr> ");
}
rs.close();
%>
</tbody>
</table>
</form>
</div>
<script type="text/javascript">
unction testfun(element, c_id) {
var x = document.getElementById('c_id');
//if check-box is checked
if (element.checked) {
x.value ="1";
} else {
x.value ="0";
}
}
</script>
how can I do ?I dont know why I can not change value?
thank.

Assign c_id to your input-box and pass same to your function i.e: testfun() with current checkbox clicked using this .Like below :
Jsp code :
out.print("<tr><td>"+"<input type='checkbox' name='a' value="+c_id+" onclick='testfun( this ,'"+c_id+"')'>"+"</td>" + "<td><input type='text' id='"+c_id+"' name='count' value=0 SIZE=5></td><td>"+name+"</td></tr> ");
Js code :
function testfun(element, cName) {
var x = document.getElementById(cName);
//if check-box is checked
if (element.checked) {
//assign required value
x.value = 1;
} else {
x.value = 0;
}
}
Demo code :
function testfun(element, cName) {
var x = document.getElementById(cName);
//if check-box is checked
if (element.checked) {
//assign required value
x.value = 1;
} else {
x.value = 0;
} }
<input type="checkbox" name="abc" value="ddnd" onclick="testfun(this,'a')" />1
<input type="checkbox" name="abc" value="ddnd" onclick="testfun(this,'b')" />2
<input type="text" id="a" />
<input type="text" id="b" />

You have getElementById but are giving it the value from the element's "name" attribute. Add id='a' to your checkbox input and it should work.

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" />

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
}
}

sum string with number onclick

I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />&nbsp Ekstra Bed <input type="checkbox" value="50000" />&nbsp Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

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