How could I write this in javascript or jQuery:
When I push the button the first time the onoff var in the change function gets the value off and the off button changes to a button named on;
now when I press the on button the var onoff gets the value on and the button changes to an off button again.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript">
function change( inputId ) {
/* ... do something with inputId ... */
var onoff = 'off';
console.log( onoff );
}
</script>
</head>
<body>
<form>
<table>
<tr>
<td>one:</td><td><input name="one" id="one" /></td>
<td><input type="button" id="b_one" value="off" onclick="change('one')"></td>
</tr>
<tr>
<td>two:</td><td><input name="two" id="two" /></td>
<td><input type="button" id="b_two" value="off" onclick="change('two')"></td>
</tr>
</table>
<br /><br /><input type="submit" value="ok"/></div><br />
</form>
</body>
</html>
This is in "pure" JavaScript. You will retrieve the button elements for given input and change its value based on the previous value.
function change( inputId ) {
var button = document.getElementById('b_' + inputId);
button.value = button.value === 'off' ? 'on' : 'off';
}
HERE is the code.
Your change() function won't work because 'off' is assigned to onoff variable everytime the function is called. You have to move the variable definition outside the change() function if you want to use it.
I'm not sure that's a valid use of value. However, something like this:
function Change(id) {
if( $("#"+id).val() == "on") {
// code for on
$("#"+id).val("off"); //switch value
}
else {
// code for off
$("#"+id).val("on"); //switch value
}
}
HTML
<input type="button" id="btnOn" value="Off" />
Javascript
var status = "off"
$("#btnOn").click(function () {
if ($(this).val() == "On") {
$(this).val("Off")
status = "Off";
}
else {
$(this).val("On")
status = "On";
}
alert("status : " + status);
});
Here is the sample : http://jsfiddle.net/JCABs
You can set event handlers without adding inline code:
$('input[type="button"]').on('click', function () {
var onoff = this.value;
//this sets the value of the input to its current opposite
this.value = (this.value == 'off') ? 'on' : 'off';
});
Here is a demo: http://jsfiddle.net/df4pu/
This also sets event handlers for every type=button input so you can reduce the repetitious code.
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().
Related
I would like to change the value of the checkbox, but failed with the following code.
$("input:checkbox").on("change", function () {
if (this.checked == true) {
this.val("1");
}
else {
this.val("0");
}
});
I not sure why it is no responds without the code, which it should've the "checked" when I'm calling this element, but no. So i will need to add a value field manually.
<input class="c-switch-input" type="checkbox" name="pk_{{$d['id']}}" value="{{$d['status']}}">
You are mixing jQuery and DOM incorrectly
EITHER
this.value = "1";
OR
$(this).val("1")
But use a ternary:
$("input:checkbox").on("change", function () {
this.value = this.checked ? "1" : "0";
console.log(this.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" />
In my (gravityform) I have two fields,a radio button or checkbox and a numeric field .
i'd like to pass a value (yes or not) to the radio button, based on the numeric field, so if i fill this with a number less than a default value for example 10 , i get the checkbox of radio button selected with "yes" or "not".
No matters if this is possible prior or after submission.
Thanks very much.
Use an event called "keyup" according to which you can change values of the radio button. Try the following code :
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#numbervalue").on("propertychange change keyup", function() {
var val = $("#numbervalue").val();
if (val > 10) {
$("#one").prop("checked", false);
$("#two").prop("checked", true);
} else {
$("#one").prop("checked", true);
$("#two").prop("checked", false);
}
});
});
</script>
</head>
<body>
<form action="">
Number:
<br>
<input type="number" name="numbervalue" id="numbervalue" value="10">
<br>
<br>Value is more than 10 ?
<br>
<input type="radio" name="truth" id="one" value="0" checked>No
<br>
<input type="radio" name="truth" id="two" value="1">Yes
<br>
</form>
</body>
</html>
Here's a very basic demo for what you are trying to do:
DEMO
The basic idea is that you look at the value in the input field and check or uncheck the radio button accordingly.
Ok thanks, this worked, awesome!!
<script>
$(document).ready(function() {
$("#input_1_38").on("propertychange change keyup", function() {
var val = $("#input_1_38").val();
if (val > 6575) {
$("#choice_1_49_0").prop("checked", false);
$("#choice_1_49_1").prop("checked", true);
} else {
$("#choice_1_49_0").prop("checked", true);
$("#choice_1_49_1").prop("checked", false);
}
});
});
</script>
You should register an event handler for the numeric input.
Pure JS solution:
var radioYes = document.getElementById("choice_1_49_0"),
radioNo = document.getElementById("choice_1_49_1"),
valueToCheck = 10;
document.getElementById("input_1_38").addEventListener("change", function() {
if (+this.value > valueToCheck)
radioYes.checked = true;
else
radioNo.checked = true;
}, false);
JSFiddle
EDIT: Updated code according to your markup.
I was trying to change the value of an variable according to the status of an checkbox
here is my code sample
<script type="text/javascript">
if(document.getElementByType('checkbox').checked)
{
var a="checked";}
else{
var a="not checked";}
document.getElementById('result').innerHTML ='result '+a;
</script>
<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>
Can you please tell me whats the problem with this code.
Try this:
if (document.querySelector('input[type=checkbox]').checked) {
Demo here
Code suggestion:
<input type="checkbox" />Checkbox<br/>
<span id="result"></span>
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = input.checked ? "checked" : "not checked";
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
</script>
In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload function, to run the code after the page loaded.
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
try something like this
<script type="text/javascript">
function update_value(chk_bx){
if(chk_bx.checked)
{
var a="checked";}
else{
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
</script>
<input type="checkbox" value="1" onchange="update_value(this);"/>Checkbox<br/>
<span id="result"></span>
Too complicated. Inline code makes it cool.
<input type="checkbox" onclick="yourBooleanVariable=!yourBooleanVariable;">
For those who tried the previous options and still have a problem for any reason, you may go this way using the .prop() jquery function:
$(document.body).on('change','input[type=checkbox]',function(){
if ($(this).prop('checked') == 1){
alert('checked');
}else{
alert('unchecked');
}
This code will run only once and check initial checkbox state. You have to add event listener for onchange event.
window.onload = function() {
document.getElementByType('checkbox').onchange = function() {
if(document.getElementByType('checkbox').checked) {
var a="checked";
} else {
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
}
I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
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.