Change variable value when checkbox is checked/unchecked - javascript

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

Related

How can i change the value of checkbox upon change

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

redirect to another page if (text area (input) === "something") when a button is clicked

This is the way I approached it. Please help:
Search
<script type="text/javascript">
var criteria = document.getElementById("search").val().toLowerCase();
if (criteria == "crosshatching") {
document.getElementById("searchBtn").onclick = function() {
window.location.href = "https://www.youtube.com/watch?v=117AN3MQuVs";
}
}
</script>
There was no scope for the variable criteria inside the function.
Also .val() is for jQuery, instead use Javascript's .value.
I've modified your code.
Please check the working code below :
document.getElementById("searchBtn").onclick = function() {
var criteria = document.getElementById("search").value.toLowerCase();
if (criteria == "crosshatching") {
alert("Matching");
window.location.href = "https://www.youtube.com/watch?v=117AN3MQuVs";
} else {
alert("NOT Matching");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="search" id="search"></textarea>
<button id="searchBtn">Search</button>
You need to check the value of your input inside the event handler. In addition, as pointed out in the comments, use value instead of val().
document.getElementById('searchBtn').addEventListener('click', function() {
var criteria = document.getElementById('search').value.toLowerCase();
if (criteria === "crosshatching") {
console.log('You would be redirected here!')
location.href = 'https://www.youtube.com/watch?v=117AN3MQuVs'
} else {
console.log('No redirect. You wrote: ' + criteria)
}
})
<input id="search" type="text"/>
<button id="searchBtn">Search</button>

Clearing textfield value

I'm trying to clear the textfield in html using javscript if the given condition is met. For ex:- if the user types awesome in textfield then it should reset the textfield (no blank space nothing).
<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
if(document.getElementById('real').value=="awesome"){
real.value='';
}
}
</script>
</html>
Here real is undefined, so instead of
...
real.value = '';
...
do this
...
document.getElementById('real').value = '';
...
Use variable real to store input element and use onkeyup event:
function blank() {
var real = document.getElementById('real');
if (real.value == "awesome") {
real.value = '';
}
}
<input type="text" id="real" onkeyup="blank()" placeholder="tempo" />
<br>
Another good example would be:
document.addEventListener('DOMContentLoaded', function() {
var real = document.getElementById('real');
real.addEventListener('keyup', blank, false);
}, false)
function blank() {
if (this.value === "awesome") {
this.value = '';
}
}
<input type="text" id="real" placeholder="tempo" />
<br>
Change the line
real.value=''
to
document.getElementById('real').value = '';
You can't just say "real.value" because javascript doesn't know what "real" is.
<html>
<input type="text" id="real" onkeypress="blank()" placeholder="tempo"/><br>
<script>
function blank(){
var real = document.getElementById('real');
if(real.value=="awesome"){
real.value='';
}
}
</script>
</html>
You where facing issue with input event "onkeypress" if change the event and use "onkeyup"
issue will be resolved.
<html>
<script>
function blank() {
var real = document.getElementById('real');
if (real.value == "awesome") {
real.value = '';
}
}
</script>
<input type="text" id="real" onkeyup="blank()" placeholder="tempo"/><br>
</html>

checkbox javascript shows status

what is problem with this script? i just want to show checkbox status in innerHTML that show "yes" after click on button, if it is checked, otherwise it shown "no".
<html>
<body>
<p id="demo"></p>
<input id="chkbox" type="checkbox" name="Terms" value="agree" ><br>
<input type="button" value="button" onClick="myFunction()" >
<script>
function myFunction() {
var box = document.getElementById("chkbox");
if(checkbox.checked)
{
var checked.value = "yes";
var txt = checked.value;
document.getElementById("demo").innerHTML = txt;
}
else if(checkbox.unchecked)
{
var unchecked.value = "no";
var txt = unchecked.value;
document.getElementById("demo").innerHTML = txt;
}
}
</script>
</body>
function myFunction() {
var box = document.getElementById("chkbox");
if(box.checked)
{
document.getElementById("demo").innerHTML = 'yes'
}
else
{
document.getElementById("demo").innerHTML = 'no';
}
}
The problems in your code were:
You set the variable box, but then used checkbox.checked instead of box.checked.
You looked for checkbox.unchecked. There's no such property; if .checked isn't true, then the box is unchecked.
You tried to declare variables checked.value and unchecked.value. Variable names can't contain ., that's used for specifying object properties when accessing a variable whose value is an object.
There are multiple problems.
There is no variable with the name checkbox
The syntax var checked.value = "yes"; is invalid
Try
<input type="button" value="button" onClick="myFunction()">
then
function myFunction() {
var box = document.getElementById("chkbox");
box.value = box.checked ? "yes" : 'no';
document.getElementById("demo").innerHTML = box.value;
}
Demo: Fiddle
Since jQuery tag is used include jQuery library in the page then
<input type="button" value="button" id="button">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and
//dom ready handler
jQuery(function ($) {
//cache the elements for future use
var $chk = $('#chkbox'), // id-selector
$demo = $('#demo');
//click event handler
$('#button').click(function () {
//use is() and :checked-selector to check whether the checkbox is checked and use .text() to set the display text of the p element
$demo.text($chk.is(':checked') ? 'yes' : 'no')
})
})
Demo: Fiddle
try:
You assigned element to box not to checkbox
There is nothing like checkbox.unchecked
var name checked.value is not correct format.
Here is code:
function myFunction() {
var box = document.getElementById("chkbox");
if (box.checked) {
document.getElementById("demo").innerHTML = "yes";
} else {
document.getElementById("demo").innerHTML = "no";
}
}
Here is working Demo
Check this one
function myFunction() {
if(document.getElementById('chkbox').checked) {
alert("checked");
} else {
alert("not checked")
}
}
try something like this,Shorthand
function myFunction(){
var box = document.getElementById("chkbox").checked;
document.getElementById("demo").innerHTML = box ? 'yes' : 'no';
}

Not Getting HTML TextBox Value in Javascript function? Have searched, but didn't find convincing answer

I'm a beginner trying to get the HTML from a textbox to be used in an if/else statement.
This is my HTML code:
<label id="label1">
Enter any Number:
</label>
<input type="button" id="Button1" value="button" />
<input type="text" id="TextBox1" name="myname" />
And my JavaScript code is:
<script type="text/javascript">
//<![CDATA[
var buttonElement = document.getElementById("Button1");
var txt_value =document.getElementById("TextBox1").value;
buttonElement.addEventListener('click', function() { Clicked(txt_value) }, false);
function Clicked(txt_value) {
if (txt_value == 7) {
alert("You are 7");
}
else { alert("You are not 7"); }
}
//]]>
</script>
I observed that
var txt_value =document.getElementById("TextBox1");
and then
buttonElement.addEventListener('click', function() { Clicked(txt_value.value) }, false);
The above example works absolutely fine.
Can someone please tell me what is wrong with:
var txt_value =document.getElementById("TextBox1").value;
I don't know why I'm getting an empty txt_value
The reason is that you are getting the value in txt_value before the user enters anything; hence the value is always empty.
IF you change your code to this:
var txt_value =document.getElementById("TextBox1");//removed .value
And the function Clicked to:
function Clicked(txt_value) {
if (txt_value.value == 7) { //added .value
alert("You are 7");
}
else { alert("You are not 7"); }
}
Should work.
Here's a jsfiddle
Move the getting of the value into the click handler...
var textbox1 = document.getElementById("TextBox1");
document.getElementById("Button1").onclick = function () {
var txt_value = textbox1.value;
if (parseInt(txt_value, 10) === 7) {
alert("You are 7");
} else {
alert("You are not 7");
}
};
Now you get the value that is in the textbox when the page loads.
Here is a JSFiddle to test this.
Update Improved the efficiency by caching the textbox. Removed the addEventListener to an onclick (more browser support)

Categories