Compare variables in Javascript - javascript

I have a script that takes in the value of input tags on a click event and I need to compare them to see if they are the same value. Iam still learning Javascript and JQuery so I really need to find some help. Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#swapCard_0").click(function(){
var phpval = document.getElementById('swapCard_0').value;
});
$("#swapCard_1").click(function(){
var phpval = document.getElementById('swapCard_1').value;
});
$("#swapCard_2").click(function(){
var phpval = document.getElementById('swapCard_2').value;
});
$("#swapCard_3").click(function(){
var phpval = document.getElementById('swapCard_3').value;
});
});
</script>
</head>
<body>
<input type="image" id="swapCard_0" src="image/image0.jpg" value="0">
<input type="image" id="swapCard_1" src="image/image1.jpg" value="1">
<input type="image" id="swapCard_2" src="image/image2.jpg" value="0">
<input type="image" id="swapCard_3" src="image/image3.jpg" value="1">
</body>
</html>
So Say a user clicks image 0 and then clicks image 2 which both have the value of 0, how can I compare them in the function then execute more code? I am sure I would need an if statement but I am not sure how to properly test it in my code. I would like to play a sound when the user clicks two different images that have the same value.

You can have a global variable and set it when user clicks on the first image like this.
$(document).ready(function(){
var selectedImageValue;
$("#swapCard_0").click(function(){
CheckValue($(this).val());
});
$("#swapCard_1").click(function(){
CheckValue($(this).val());
});
$("#swapCard_2").click(function(){
CheckValue($(this).val());
});
$("#swapCard_3").click(function(){
CheckValue($(this).val());
});
function CheckValue(value)
{
if(selectedImageValue != '')
{
selectedImageValue = value;
}
else
{
if(selectedImageValue === value)
{
//Your logic when image contains the same value
}
}
}
});

What i would do if i was you is the following:
Pass a class to all images so you can handle them with one click listener. e.g. class: .image
var phpval;
$('.image').on('click', function() {
if (phpval && phpval === this.value) {
//play sound here
} else {
phpval = this.value; //set php to this value
}
});

I would make several changes. First, I would put a class on all of your cards so that you can target all of them with a single selector. Then I would use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var prev_click;
$(function(){
$('.swapCard').click(function(){
var this_click = this.value;
if(prev_click === this_click){
playSound();
}
else{
prev_click = this_click;
}
});
});
</script>
</head>
<body>
<input type="image" id="swapCard_0" class="swapCard" src="image/image0.jpg" value="0">
<input type="image" id="swapCard_1" class="swapCard" src="image/image1.jpg" value="1">
<input type="image" id="swapCard_2" class="swapCard" src="image/image2.jpg" value="0">
<input type="image" id="swapCard_3" class="swapCard" src="image/image3.jpg" value="1">
</body>
</html>
This code listens for a click. It then compares the previous click value with the current click value. If they match, it plays a sound. If they don't, it stores the current click value for the next comparison. I think this accomplishes what you're trying to do.

Related

Input event not working if value is changed with jQuery val() or JavaScript

If I change the value of an input field programmatically, the input and change events are not firing. For example, I have this scenario:
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The problem: The event is triggered when I type in the textfield, but not when I press the button. Is there a way to achieve this with some kind of event or otherwise without having to do it manually?
What I don't want to do: I could go through all my code to add a trigger or function call everywhere manually, but that's not what I'm looking for.
Why: The main reason I would like to do this automatically is that I have a lot of input fields and a lot of different places where I change these inputs programmatically. It would save me a lot of time if there was a way to fire the event automatically when any input is changed anywhere in my code.
Simple solution:
Trigger input after you call val():
$input.trigger("input");
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
// Change the value and trigger input
$input.val($input.val() + 'x').trigger("input");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="myinput" type="text" />
<button id="change">Change value</button>
Specific solution:
As mentioned you don't want to trigger input manually. This solution triggers the event automatically by overriding val().
Just add this to your code:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
var res = originalVal.apply(this, arguments);
if (this.is('input:text') && arguments.length >= 1) {
// this is input type=text setter
this.trigger("input");
}
return res;
};
})(jQuery);
See JSFiddle Demo
PS
Notice this.is('input:text') in the condition. If you want to trigger the event for more types, add them to the condition.
There are some ways on how to achieve it. Here, you can use the levelup HTML's oninput() event that occurs immediately when an element is changed and call the function.
<input id="myinput" type="text" oninput="sample_func()" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
function sample_func(){
alert(input.val());
}
$('#change').click(function() {
input.val(input.val() + 'x');
});
Or this jQuery, input thing (just related to above example).
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
input.on("input", function() {
alert(input.val());
});
$('#change').click(function() {
input.val(input.val() + 'x');
});
You can also use javascript setInterval() which constantly runs with a given interval time. It's only optional and best if you're doing time-related program.
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
setInterval(function() { ObserveInputValue(input.val()); }, 100);
$('#change').click(function() {
input.val(input.val() + 'x');
});
jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.
You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so:
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function:
$("#myInput").changeTextField("foo");
Here's a version working with a proxy function:
<!DOCTYPE html>
<html>
<head>
<title>Test stuff</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<input id="myInput" type="text" />
<button id="myButton">Change value</button>
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
</body>
</html>
For reference, this question has really already been answered here:
Why does the jquery change event not trigger when I set the value of a select using val()?
and here: JQuery detecting Programatic change event
Looks like there's no way, other than using .trigger().
Let's try the same thing using .change() event:
var $input = $("#myinput");
$input.on('change paste keyup', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("change");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or you need to trigger it manually:
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
Snippet
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trigger didn't work for. Creating an event and dispatching with native JavaScript did the work.
Source: https://stackoverflow.com/a/41593131/6825339
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).dispatchEvent(new Event("input", { bubbles: true });
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
$input.val($input.val() + 'x')
$input.trigger('change');
The change event only fire when input blur.
Try this
$('#input').trigger('change');

Pass value (yes or not) to radio button in same form

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.

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>

Copy text of a field into another automatically

I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>

How to disable input attribute after 10 clicks?

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>

Categories