How to define local variables in a jQuery .on function - javascript

I have an input HTML element and want to execute a function when there was an input and if this input didn't changed for 3 seconds.
Code:
$("#search_input").on('input', function() {
input_value = $("#search_input").val();
if (input_value != "") {
setTimeout(function() {
if (input_value == $("#search_input").val()) {
alert("still the same :) -> go search");
}
}, 3000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="search_input" placeholder="Search...">
The problem is that the handler refresh the input_value so it's always the same. How do you set the input_value as a local variable, so it's not refreshed?

You forgot the var declaration:
var input_value = $("#search_input").val();

while the var thing is true, it's unlikely the issue.
Looks like you want something like the link below, with the key difference being that you are setting a timeout and clearing the timeout as the input changes. By definition, the function above is always firing when input is changing so it's redundant.
Run javascript function when user finishes typing instead of on key up?

var var_name = value if it's a normal variable. Like a string or number.
Do $var_name = jQuery_object if it's a jQuery object.

Related

jQuery nested functions

I am still new to JavaScript and jQuery, so I am confused as to why the following code is not working as I anticipated. All I am trying to do is save input on a button click (id=recordInput) and display it with another button click (id=displayInput). What I observe is that tempInput is stored, (the code works until that point) but assignment of displayInputs onclick attribute is not executed. My question is, can you not nest a $().click() call inside of another &().click() call?
<script>
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
</script>
My thinking is this in pseudocode:
assign recordInput onclick attribute to the following function:
store tempInput
set displayInput onclick to alert the tempInput value
what is wrong with my thinking?
NOTE: I did not include any html tags but all of the ids are referenced correctly
It's not working because you have put & instead of $ here
$('#displayInput').click(function(event) {
Fixing this may work, but you shouldn't set event handlers this way. Because every time your first handler function is called it will set an event handler for the second one. You can try with your console.log and you will see that the number of console.log is increasing by every click on #recordInput. So you should better set it like this :
var tempInput;
$('#recordInput').click(function(event) {
tempInput = $('#testInput').val();
});
$('#displayInput').click(function(event) {
console.log(tempInput);
});
I would change
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
to
$(function(){
var testInput = '';
$('#recordInput').click(function(){
testInput = $('#testInput').val();
});
$('#displayInput').click(function(){
if(testInput !== ''){
console.log(testInput);
}
});
});
You are using & instead of $. Of course, you don't have to format the code exactly like I did.

Return value from input field with the jQuery blur function

Goal: User focuses input field. User writes a value in input field. When user is done and the input field isn't in focus anymore, save inserted value to a variable called 'inputFieldValue'. This is should be done invoking the function 'returnInputValue'.
html
<!DOCTYPE html>
<html>
<head>
<title>My test</title>
</head>
<body>
<input class="input" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
test.js
function returnInputValue() {
var inputValue;
$('.input').blur(function() {
inputValue = $('.input').val();
});
return inputValue;
}
var inputFieldValue = returnInputValue();
When I call the variable inputFieldValue variable from the console after having inserted a value and focused out again, it is still 'undefined'.
Have I missed something?
The function you execute is an asynchronous function, i.e., it is based on the time after the input triggers a blur event. You need to either return it inside the blur event:
function returnInputValue() {
var inputValue;
$('.input').blur(function() {
inputValue = $('.input').val();
return inputValue;
});
}
As suggested by some, even above code is not correct. The inputValue doesn't work as it always returns undefined.
Or, set it up to directly access the last blurred value.
var inputValue = "Not Blurred Yet!";
$('.input').blur(function() {
inputValue = $('.input').val();
});
function returnInputValue() {
return inputValue;
}
This is the current logic:
Initialize a variable that has an undefined value.
Bind a handler which is executed at undefined junctures, the variable is still undefined.
Return the undefined value immediately
The above logic is broken and should be rectified. The best option is moving the final logic into the blur handler:
$('.input').blur(function() {
var inputValue = this.value;
// do something with the value
// ...
});
If you need to get the value at a certain juncture, query the DOM, select the element and get it's value.
Try to declare variable outside the function
<script>
var inputValue;
function returnInputValue() {
$('.input').blur(function() {
inputValue = $('.input').val();
});
return inputValue;
}
var inputFieldValue = returnInputValue();
</script>
You could use.
$(document).on("blur","#Yourinput",function(){
var Myval = $("#Yourinput").val();
// Execute your code here I.e call your function
// ...
// You do not even have to call you function put
// It in a div to display
$("#yourdiv").html(Myval);
//Will display it in a div
//Or add to array
Yourarray.push(Myval);
});
This uses jQuery .on() method.
This method is very flexible. If your inserting into a database you can do that here too quite simply with jquery ajax.
You have to play with the events I.e replace blur with another event but if your using jquery this I believe is the simplest method

How to count string length, if length equals X, then execute code? - JavaScript

Using JavaScript, I want to call an anonymous function that checks the length of a string for every onkeyup event. When the string length equals 9, a conditional statement will execute a block of code. What am I doing wrong?
<input type="text" id="length_test" placeholder="Enter text here..." />
var length_test = document.getElementById('length_test');
var string_value = document.getElementById('length_test').value;
var x = 9;
length_test.onkeyup = function () {
if (string_value.length == x) {
// execute code here...
}
}
Give the following a try.
Note: The example below uses JQuery. If you didn't wait to use JQuery that is fine.
You could natively do it with the following.
document.getElementById("length_test").addEventListener("keyup", myFunction);
You would need to then create a function called myFunction that has your if statement in it.
$(document).ready(function() {
$("#length_test").on("keyup", function(event) {
if (event.currentTarget.value.length == 9) {
//do your logic here
alert("length is 9");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="length_test" placeholder="Enter text here..." />
document.getElementById returns a live node. This means that any changes happening to the actual element in the page will be reflected on the object. When you write something else in the field, the value property of the element gets updated. However, the value stored in string_value doesn't get updated, since it's just a good old string, not some kind of live object.
Another way to see it is that
var string_value = document.getElementById('length_test').value;
makes a copy of the element's .value and stores it in string_value (even though that's not exactly how it works). When you type in the input, it updates the .value but not the string_value variable.
But what you should do is:
document.getElementById('length_test').addEventListener("keyup", function(e) {
if(e.target.value.length === 9) {
alert("length is 9");
}
});
This is much better because document.getElementById is only executed once, when binding the event. Event listener functions can revieve the event through their first argument (commonly named e). e.target is the element which called the event, in this case the input element.
You could try:
<input type="text" id="length_test" placeholder="Enter text here..." onkeyup="keyupFunction()">
<script type = "text/javascript">
keyupFunction function () {
if(document.getElementById('length_test').value == 9) {
// execute code here...
}
}
</script>
Alternatively, you could use javascript to add an event listener to the input element:
<input type="text" id="length_test" placeholder="Enter text here...">
<script type = "text/javascript">
document.getElementById('length_test').addEventListener("keyup", function(evt) {
if(document.getElementById('length_test').value == 9) {
// execute code here...
}
});
</script>

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

textarea.val() value changing but not displaying on page

I have a textarea like so,
<textarea id="txtaFilter" cols="45" rows="5"></textarea>
and the following script,
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
$("#txtaFilter").val($("#txtaFilter").val() + value);
$(this).children('option:eq(0)').prop('selected', true);
});
});
where ".selector" is a class applied to two dropdownlists.
When I chose a value on the dropdown, it appears to do nothing, but after looking at the debugger in chrome it is changing the value just not displaying it.
Does anyone know why this is? Is there something special I'm missing about the .val() property?
Problem/Solution:
I forgot that there are multiple "#txtaFilter"'s on the page when I removed the $(this).siblings("#txtaFilter"), So it was accessing the hidden one instead of the visible one. Sorry about that, guess I was wrong on the question too :/
You can use val method:
$("#txtaFilter").val(function(i, oldVal){
return oldVal + value
});
Use .val() to get the text of a textarea.
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
var txtaFilter = $("#txtaFilter");
txtaFilter.val(txtaFilter.val()+value);
$(this).children('option:eq(0)').attr('selected', true);
});
});

Categories

Resources