I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">
Related
I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.
I have the following code. I need to see how many checkboxes have been checked in my form and if there are more than four display error and uncheck the last check box,everything is working but how can I uncheck the last check box, thanks
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I think that I would handle this differently. I'd have a click handler on each checkbox that counts the number of checked boxes (including the current if it is being checked) to see if it is greater than 4. If it is, then I would stop the current event, pop the alert, and reset the state of the checkbox causing the alert. This way it would always popup when clicking the fourth checkbox.
To handle the case where javascript is disabled, you'd need to make sure that your server-side code validates that no more than 4 checkboxes have been checked.
JQuery example:
$(':checkbox').click( function() {
if ($(this).val() == 'on') { // need to count, since we are checking this box
if ($(':checkbox:checked').length > 4) {
alert( "You can only choose up to a maximum of 4 toppings." );
$(this).val('off');
}
}
});
Note if you had other types of checkboxes on the page you could use a class to distinguish them. In that case, the selector becomes (':checkbox.topping') and (':checkbox.topping:checked').
Keep track of the last checked checkbox and set its checked property to false:
// ...
var lastChecked; // Will be used in loop below
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
lastChecked = i; // Store the checkbox as last checked
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
checks[lastChecked].checked = false; // Uncheck the last checked checkbox
} else {
// ...
If you want to uncheck all but the four first ones, do it like this:
// ...
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
if (totalChecked > 4) checks[i].checked = false; // Uncheck checkbox
}
}
Well you'll need to somehow pass into this method which particular checkbox was just checked, and then if the total checked count test fails, then just set that checkbox's .checked property to false.
What if the user checked more than five?
One way to do it is create a javascript function that returns false if more than four checkboxes are checked. In each checkbox, hook the new function like this:
<input type="checkbox" onclick="return myNewFunction(this);">
This will inhibit the user from checking any checkbox that is the fifth one.
Alternatively, you could prevent the user from making an invalid action in the first place, by disabling all the other boxes once four of them are checked, and displaying a message like "Choose up to four of these." This way, you don't let the user do something you know is invalid and then scold them.