jQuery "this-reference" not set after load event - javascript

I don't understand why the "this-reference" in function foo
is not set with #searchval, when called by load event ?
The function call of foo at the keyup event works but the call does not work at the load event cause this-reference is not set.
Example:
<body>
<form action="" method="post">
<input type="text" name="test" value="<?=$_POST['test']?>" id="searchval">
<select id="names" size="3">
<option value="1">WTF1</option>
<option value="2">WTF2</option>
<option value="3">WTF3</option>
</select>
<input type="submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
var names = $('#names option').clone();
function foo() {
//Change the code to $('$searchval').val(); make it work
var val = $(this).val();
$('#names').empty();
names.filter(function(idx, el) {
return val === '' || $(el).text().indexOf(val) >= 0;
}).appendTo('#names');
}
$('#searchval').bind('keyup', foo);
$('#searchval').load(foo());
});
</script>
</html>

You're setting up the handler with the return value from "foo", not the function itself.
It should be:
$('#searchval').load( foo );
When you pass foo(), you're first invoking the function — that's what ( ) does. By passing just the function reference you get the effect you want.
edit — on top of that issue, as noted in a comment you're trying to set up a "load" handler for an element that'll never get such an event. What is it that you expect to cause that event? Perhaps "change" is what you want instead of "load".
edit again — if you just want to simulate having "foo" called as it is when a "keyup" event happens, you can do two things:
You can use "triggerHandler":
$('#searchval').triggerHandler('keyup');
You can use "call":
foo.call($('#searchval')[0]);
In both cases, of course, you won't get an "event" object that's like the one you get on a real event, but "foo" doesn't care about that anyway.

Related

Jquery to take value inside function onclick

This little script to take values from select
<script>
jQuery(document).ready(function()
{
var clv1=jQuery("#tr_val").val();
});
</script>
When click over this div and execute function open_win, i need send value of select inside function jQuery("#tr_val").val();
<div onclick="open_win(""+clv1,'test');">Test</div>
The problem it´s i don´t know how writte right syntax for insert value "clv1" inside function open_win when click over div Test
I have only this problem, i try different combinations but no works me never
Thank´s in advanced
You can add a global variable, and on change of your select you can modified that variable.
While on div element you can add id, and write event handler into script tag(here you can access that global variable).
Note: However global variable are not the correct way, but you can do it for learning/testing.
I think this is what you are asking for, I've re-organised things a little. There is now a custom function that you call from the inline onclick of the div. Rather than trying to grab the value on document ready you can do it with the click, I think this simplifies the process.
Let me know if this isn't what you were hoping for.
Demo
// Add a function which you call from the inline onclick
function open_win() {
// Gather the value of the input
console.log( $("#tr_val").val() );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="tr_val" value="one">
<div onclick="open_win()">Test</div>
You may try something like this, store the value on the div's data attribute and then access it inside the function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
function open_win(){
$(this).data("val", $("#tr_val").val());
console.log($(this).data('val'));
}
</script>
<div onclick="open_win()">Test</div>
<select id="tr_val">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
Note: your open_win function must be defined before calling it.
if you want to get the value of the element with the id tr_val when you click on the div try something like this. put the click event in the javascript as well. Also if you want to run a function like you're trying to do inline you need to have that function defined, but can also use it in the script tags/js file
function open_win(someArg) {
// do something
}
<div class="test-class">Test</div>
<script>
$(document).ready(function() {
var clv1 = $("#tr_val").val();
// anonymous function
$('.test-class').on('click', function(e) {
console.log(clv1);
})
// named function with a parameter
$('.test-class').on('click', function(e) {
open_win(clv1);
})
// if you wanted named function with parameter to look a bit cleaner
// using es6 arrow function
$('.test-class').on('click', (e) => open_win(clv1))
// name function no param (event is the first argument passed in by default but you can't pass params in like this)
$('.test-class').on('click', open_win)
});
</script>
You can use ES6 ways
<h1>Hello World!</h1>
<input id="tr_val" value="element value" hidden>
<div class="open-div" data-text='test'>Test</div>
(function ($) {
$(function () {
let tr_val = $('#tr_val').val();
$('.open-div').on('click', function (e) {
let $this = $(this);
let text = $this.data("text");
console.log(tr_val);
console.log(text);
});
});
})(jQuery);
https://codepen.io/nsivanoly/pen/OemWNM

JQuery event listener call function by name with parameters

I have seen other questions similar to this one, but I cant seem to find the answer i'm looking for.
Is there any way of passing parameters into a named function in a JQuery event listener?
For example, I know I can do this
$('#myelement').on("change", function(){
var value = $(this).val();
myFunction(value);
});
But is there any way to just pass the function name into the event listener instead?
Something like this
$('#myelement').on("change", myFunction($(this).val()));
I thought it would be straight forward to be honest, but I can't seem to find a way to do it.
You can pass parameters to the handler function using jQuery .on() method.
Its format is .on( events [, selector ] [, data ], handler ), where data is any object you need to pass. Later it can be accessed via event.data property in the handler.
Check this example. Note that if you just want to access $(this).val() then you don't need any parameters: myFunction is already bound to the target element, so you can use $(this).val() inside of it.
$("#i").on("change", null, "My parameter", myFunction);
function myFunction(event) {
console.log("Parameter: " + event.data);
console.log("$(this).val() = " + $(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="i"> Enter something and press Enter
You can use the jQuery "on" method, then invoke the click event listener and last but not least call the function that you created.
$('button').on('click', clicked);
function clicked() {
var val = $('#one').val();
$('.response').html('<p>Value is ' + val + '</p>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="one">
<button>Click Me</button>
<p class="response"></p>
Assuming I understand what you want, one workaround I've used is to refer to functions in an array like follows
list_of_functions = [function_1,function_2];
function function_1(){
alert("function 1 running");
}
function function_2(){
console.dir("function 2 running");
}
function run_function(function_index){
return list_of_functions[function_index]();
}
$("#function_select").on("change",function(){
run_function(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="function_select">
<option disabled selected>Please select a function</option>
<option value="0">function 1</option>
<option value="1">function 2</option>
</select>

callback function with universal argument handling

I would like to make a JS function which handles its arguments independedently from where it is called.
AFAIK the arguments differ, depending where the function is called.
Example 1
A commom usage is to register the function in HTML:
<input type="text" id="text1" onkeyup="myFunc(this);">
The element will then be passed on to the function:
function myfunc(element) {
alert(element.value);
}
Example 2
Another, appoach is to register it dynamically, when the document is finished loading. Something along those lines:
// init() gets called when document is ready
function init() {
document.getElementById('text2').addEventListener('keyup', myFunc2);
}
Now the function will receive an Event-Object instead of an Element-Object.
I need to change the functions code to access the information.
function myFunc2(event) {
var element = event.target;
alert(element.value);
}
Example 3
One way to solve this problem would be to completely ingnore arguments and always gather all information inside the function, like this:
function myFunc3(event) {
var element = document.getElementById('text3');
alert(element.value);
}
The ugly thing about this solution is, that the GUI will be thigtly coupled to the logic.
Example 4?
One solution I can think of would be to change Solution 1 and pack the this into an Event-Object? I have not tried this yet and I'm not sure how to do this most elegantly.
Ps: No JQuery "allowed"
The first one can be rewritten like this (note that it's preferred not to mix your markup with event handlers, however if you really want it to, then it can be written like this)
<input type="text" id="text1" onkeyup="myFunc(event);">
and the second one will take the input from the events target property.
function myFunc(e) {
let element = e.target;
console.log( 'event comming from ' + element.id );
console.log( 'current value is ' + element.value );
}
window.addEventListener('load', function() {
let el = document.querySelector('#text2');
el.addEventListener('keyup', myFunc);
});
<input type="text" id="text1" onkeyup="myFunc(event);">
<input type="text" id="text2">
This covers both cases:
function foo(e) {
let element = e.target || e;
}
You could have your function check the instance/type of the argument(s) and delegate the logic to other functions.
function myGeneralFunction(arg) {
if(arg instanceof Event) {
return handerForEvents(arg);
}
return otherHandler(arg);
}

Run AJAX script

I have the ajax, which runs when the user writes something ind input id=2
HTML:
<input id="2" type="text" onkeyup="posttitulo(this.value)" />
SCRIPT:
function posttitulo(value){
$.post("getdata/posttitulo.php",{partialStates:value});
}
The code works perfectly.. The problem is that I have the javascript function which onclick copies value of another input id=1, in this case id=2 has the value without typing and function posttitulo(value) doesn't work..
So I need Ajax to be executed if:
1) User writes something onkeyup="posttitulo(this.value);
2) the value of id=1 is copied to id=2..
Hope that I explained the problem..
Thanks in advance
Do $('#2').keyup(); after you copied a value in the function, which fires onclick.
create an event listener change() on id=2:
$(document).ready(function(){
$("#2").change(function(){
var value=$("#2").val();
$.post("getdata/posttitulo.php",{partialStates:value});
});
});
You could go with firing the event on the input or recycle the function you already declared. When the button is clicked read the value of the id2 Element and call the posttitulo function with the value as argument.
function posttitulo(value){
console.log('AJAX POST:', value);
}
function buttonClicked() {
var value = document.getElementById('id2').value;
posttitulo(value);
}
Fiddle
May be this will work in your case.
<input id="1" type="text" onclick="yourreplacefunction(this.value,2)" />
$(document).on("change keyup", "input", function() {
$.post("getdata/posttitulo.php",{partialStates:value},function(response){
//Do with your response
});
});
function yourreplacefunction(value,toid) {
$('#'+toid).val(value);
}

Copy value from input 1 to input 2 onclick

Looking for a script that copies input value 1 to input 2 on button click and add +1 to sets text box.
b = document.getElementById('tussenstand').value;
var theTotal1 = b;
$(document).on("click", "#button1", function(){
theTotal1 = Number(theTotal2)
$('#eindstand').val(theTotal2);
});
$('#eindstand').val(theTotal2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1">click</button>
Thanks in advance.
I think this will do it.
$(document).on("click", "#button1", function(){
var total = document.getElementById('tussenstand').value;
$('#eindstand').val(total);
var sets = parseInt($('#sets').val());
$('#sets').val( (sets || 0) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="tussenstand"></input>
<input id="eindstand"></input>
<input id="sets"></input>
<button id="button1" onclick="">click</button>
$('#button1').click(function(){
$('#eindstand').val($('#tussenstand').val());
$('#sets').val(Number($('#sets').val())+1);
});
check here : jsfiddle
Edited as you commented
The code below should work. There are several issues that will help you in the future. In the HTML the function that is triggered via the onclick will interfere with the jQuery onclick. You may want to remove it.
onclick="bereken();
The way that you have your code the b variable is not declared.
b=document.getElementById('tussenstand').value;
The way that the jQuery onclick is written should have a narrower scope (not the document). The way that it is now every time you click any were in the document it fires. I changed this:
$(document).on("click", "#button1", function(){
to this:
$("#button1").on("click", function() {
The full edited code is here.
var count = 0;
$("#button1").on("click", function(){
if ( typeof b === 'number') {
count++;
$("#eindstand").val(b);
$("#sets").val(count);
}
});
Look at the JQuery API Documentation for the .on() method. The function doesn't take the target as a parameter, but as the caller object! EDIT: well, it would actually still work the other way around, but that makes event delegation. Only do that if you know what you're doing. I prefer changing this:
$(document).on("click", "#button1", function(){ ... });
into this:
$("#button1").on("click", function() { ... });
Which in vanilla JS would be:
document.getElementById("button1").addEventListener("click", function() { ... });
Next, you shouldn't need to define variables outside of your function, and naming variables with numbers in them is a bad practice. Try to make the names as clear as possible.
Now that this is clear, here's how I'd write it:
$("#button1").on("click", function() {
$("#eindstand").val($("#tussenstand").val());
$("#sets").val(parseInt($("#sets").val())+1);
});
To achieve that use:
$(function() { //on DOM ready
$('#button1').click(function(){ //Attach event
//Get value safe - can use parseFloat() too:
val1 = parseInt($('#tussenstand').val());
val2 = parseInt($('#eindstand').val());
sets = parseInt($('#sets').val());
//Make sure we are using integers:
if (isNaN(val1) || isNaN(val2) || isNaN(sets)) return;
//Add
$('#eindstand').val(val1 + val2);
//Increment:
$('#sets').val(sets+1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="tussenstand" type='number' />
<input id="eindstand" value='0' type='number' />
<input id="sets" value='0' type='number' />
<button id="button1">click</button>

Categories

Resources