I have a select option that calls a function that needs to be triggered on change. But now it's triggered when the page is loaded and on change. See below:
$(function () {
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
$('select[id^="iZondageinde_"]').on('change', uren("Zondag"));
$('select[id^="iMaandagBegin_"]').on('change', uren("Maandag"));
$('select[id^="iMaandageinde_"]').on('change', uren("Maandag"));
$('select[id^="iDinsdagbegin_"]').on('change', uren("Dinsdag"));
$('select[id^="iDinsdageinde_"]').on('change', uren("Dinsdag"));
$('select[id^="iWoensdagbegin_"]').on('change', uren("Woensdag"));
$('select[id^="iWoensdageinde_"]').on('change', uren("Woensdag"));
$('select[id^="iDonderdagbegin_"]').on('change', uren("Donderdag"));
$('select[id^="iDonderdageinde_"]').on('change', uren("Donderdag"));
$('select[id^="iVrijdagbegin_"]').on('change', uren("Vrijdag"));
$('select[id^="iVrijdageinde_"]').on('change', uren("Vrijdag"));
$('select[id^="iZaterdagbegin_"]').on('change', uren("Zaterdag"));
$('select[id^="iZaterdageinde_"]').on('change', uren("Zaterdag"));
function uren(dag) {
var vandaag = datumvandaag();
var pauze = ($('[title="Pauze"]').val());
var error;
$('input[id^="i' + dag + '_"]').val("");
//get values
var tijdStart = ($('select[id^="i' + dag + 'begin_"]').val());
var uurStartControle = +($('select[id^="i' + dag + 'begin_"]').val());
tijdStart += ":" + ($('select[id^="i' + dag + 'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
var minutenStartControle = +($('select[id^="i' + dag +'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
//var datezondagstart = new Date(vandaag + tijdstart + ":00");
var tijdStop = ($('select[id^="i' + dag + 'einde_"]').val());
var uurStopControle = +($('select[id^="i' + dag + 'einde_"]').val());
tijdStop += ":" + ($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
var minutenStopControle = +($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
if (uurStartControle >= uurStopControle && minutenStartControle >= minutenStopControle || uurStopControle <= uurStartControle) {
alert("Tijd is ongeldig!");
error = 1;
}
if (error != 1) {
var totaleTijd = tijdsverschil(tijdStart, tijdStop, pauze);
if (totaleTijd != '00:00') {
$('input[id^="i' + dag + 'uren_"]').val(totaleTijd);
}
else{
alert("Tijd is ongeldig!");
}
}
}
});
Any one have an idea what i'm doing wrong? I'm i call it the wrong way?
Currently You are calling uren function when you are using uren("Zondag"). You should use an anonymous function as event handler and call uren function.
Use it like
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
To:
$('select[id^="iZondagbegin_"]').on('change', function () {
uren("Zondag");
});
I would recommend, You to use data-* attributes to store what need to be passed to change event handler.
Example:
HTML, Here Added a cooom class mySelect
<select class="mySelect" id="iZondagbegin_1" data-value="Zondag"> .... </select>
<select class="mySelect" id="iMaandagBegin_" data-value="Maandag"> .... </select>
Script
$('.mySelect').on('change', function () {
uren($(this).data('value'));
});
There's already two answers that point out your issue; an alternative solution is to let jQuery handle contexts with $.proxy:
$('select[id^="iZondagbegin_"]').on('change', $.proxy(uren, null, "Zondag");
More info here
Please change all lines like:
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
To:
$('select[id^="iZondagbegin_"]').on('change', uren);
and:
<select id="iZondagbegin_...." data-value="Zondag">.....</select>
and:
function uren() {
var value = $(this).data('value');
//.....
}
Or better still, use a common class, .myclass say, on all the select elements and do the binding with one statement.
$('select.myclass').on('change', uren);
.....
<select id="iZondagbegin_...." data-value="Zondag" class="myclass">.....</select>
.....
function uren() {
var value = $(this).data('value');
//.....
}
When you pass arguments like that or when you provide (), the function will be invoked immediately. You don't want that.
Related
I have asked something similar in the past but was able to resolve it by separating the functions by events. I need to be able to pass 2 href events in one Onchange Event because it is a dropdown, OR I need to be able to tie the second function into another Event.
This works only when an alert() is inserted. Once I take the alert() out it does not work. I've tried to supress the alert while still keeping it in the code and it works fine. I do not want the alert but I want the results.
HTML Here:
<select id="PartList" class="form-control form-control-lg ml-0" onChange="SelectMain();">
JavaScript Here
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1 HERE='+ "'" + text + "'" ;
//alert(value);
//alert(text);
window.location.href = str;
}
function SelectValue() {
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2 HERE' + value ;
alert(value);
window.location.href = str;
}
function SelectMain() {
sList();
SelectValue();
}
function alert(message) {
console.info(message);
}
This is resolved, for those that come to this question. The problem wasn't with the JavaScript it was because the device I was sending the commands to couldn't handle the commands that fast. I have incorporated the resolved code with troubleshooting techniques.
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1='+ "'" + text + "'" ;
//str1 = 'http://google.com';
//alert(value);
//alert(text);
window.location.href = str;
//window.open(str1);
}
function SelectValue() {
setTimeout(function(){
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2=' + value ;
//str1 = 'http://aol.com';
//alert(value);
window.location.href = str;
//window.open(str1);
},1000);
}
Hi everyone i have one question about jquery click send function. I have created this demo from jsfiddle. So if you visit the demo then you can see there is one smiley and textarea. When you write some text and press enter then the message sending successfully. But i want to add also when you click the smiley then it need to send (w1) from the image sticker="(w1)" like click to send. But click send function doesn't work. What is the problem on there and what is the solution ? Anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function() {
$('body').on("click",'.emo', function() {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function(event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if(msg == ''){
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
});
HTML
<div class="container one">
<div class="comments-area" id="commentload47">comments will be come here</div>
<div class="user-post" id="postbody47">
<textarea class="sendcomment" name="comment" id="commentid47" data-msgid="47"></textarea>
<div class="stiemo">
<img src="http://d.lanrentuku.com/down/png/1009/networking/emoticon_inlove.png" class="sm-sticker emo" sticker="(w1)"> click smiley to send (w1)</div>
</div>
</div>
</div>
try this :
just append below JS after the line theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
Demo
you should use this:
$('body').on("click",'.emo', function() {
var ID = $('.sendcomment').attr("data-msgid");
var comment = $('.sendcomment').val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
so basically instead of this you have to use input and get msgid and val from there, use same approach for rest.
So when you are attaching event on some button and you want to use data from some other dom element you have to get that element by using $(selector) under your delegated function, really simple approach.
I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>
I have this line of code that exist in a partial view. Jquery code resides in the index page hosting the partial view
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I have a checkbox on every row of data. This is all within a webgrid. Here is what it looks like below
#{
var gridColumns = new List<WebGridColumn>();
gridColumns.Add(grid.Column(format: (item) =>
{
var s = "<input type=\"checkbox\" name=\"InvoiceNumber\" id=\"IN" + item.InvoiceNumber.ToString() + "\" value=\"" + item.InvoiceNumber.ToString() + "|" + item.AmountDue + "\"";
if (item.IsSelected) {
s += "checked=\"true\"";
}
s+= "/>";
return s;
}
, style: "box"));
...
...
...
}
function SetViewSelected(c) {
var s = 0;
for (i = 0; i < $("input[name='InvoiceNumber']:checked").length; i++) {
invoice_details = $("input[name='InvoiceNumber']:checked")[i].value;
invoice_amount = invoice_details.split("|")[1];
s += parseFloat(invoice_amount);
}
alert(s);
//$('.paythisamountbtn').val(s);
}
As I check and uncheck the checkboxes, I want to be able to show the total on the line below as they change. At the moment the alert(s) gets me the new total
<div class="paythisamountbtn">#Html.ActionLink(T("Pay This Amount"), "InvoiceCheckout", null, new { #target = "InvoiceCheckout", #class = "amebtn" }): #String.Format("{0:C}", Model.TotalDue)</div>
I tried doing $('.paythisamountbtn').val(s); but the totaldue does not change as I check and uncheck the check boxes.
How can I do this please?
Use .text for a div
$('.paythisamountbtn').text(s)
To update the attribute value what you must do is the following:
$('.paythisamountbtn').text(parseInt($('.paythisamountbtn').text())+5);
To update the value each time you click one of the checkboxes you could do something like this:
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
UpdateValueNow();
}
});
I am trying to call a function using each object found in jQuery selection
a
b
c
d
Each a element has a data-code value:
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
Each p element has a data-value:
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$("output").each(Display(code));
});
});
What I want is that when you click on the anchor a you will get an alert showing you the data-code from the anchor clicked and the data-value for each p, with the code attached I want 3 alerts to pop up.
function Display(code) {
var p = $(this);
var value = p.data("value");
alert(code + " " + value);
}
Here is a link to the code in jsfiddle: http://jsfiddle.net/mikeu/XFd4n/
You have to use . for class-selectors and pass this object when you are calling Display function like,
$(document).ready(function() {
$(".can-click").click(function(e) {
e.preventDefault();
var code = $(this).data("code");
$(".output").each(function() { // use . for class selectors
Display(code, this); // pass this from here
});
});
});
function Display(code, ths) { // ths = this, current output element
var p = $(ths), // use ths instead of this
value = p.data("value");
console.log(code + " " + value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
a
b
c
d
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
Try this:-
You need to pass in function reference to the obj.each callback. obj.each(Display(code)) is wrong, it should be obj.each(Display) ; but since here you want to pass in the variable, you can invoke it inside an anonymous function.
Demo
$(".output").each(function(){
Display(code, this)});
});
Script
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$(".output").each(function(){
Display(code, this)});
});
});
function Display(code,$this) {
var p = $($this);
var value = p.data("value");
alert(code + " " + value);
}