Pass 2 Functions Through One OnChange Event - With HREF on both Functions - javascript

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

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

Alternate code for "if else" in my code

Below given was my javaScript code.
Condition is, If I give a word like hello. the image for a hello should be displayed or if I give facebook, the image for that has to be displayed likewise for many words, the mentioned image has to be displayed.. But here in my code condition gets failed after first time and image is not displaying for the second word.
Help me with the alternate code for the above mentioned problem
var anu = document.getElementById("display");
var a= document.getElementById("final_span").textContent;
console.log(linebreak(interim_transcript));
if(a.search("hello") || a.search("facebook")){
if(linebreak(interim_transcript) == "hello"){
anu.innerHTML="<img src=hello.jpg>";
}
else if(linebreak(interim_transcript) == "facebook"){
anu.innerHTML="<img src=facebook.jpg>";
}
else if(linebreak(interim_transcript) == "hi"){
anu.innerHTML="<img src=hi.jpg>";
}
else if(linebreak(interim_transcript) == "doll"){
anu.innerHTML="<img src=doll.jpg>";
}
If the value returned by linebreak and image name are same you can use
anu.innerHTML = '<img src="' + linebreak(interim_transcript) + '">';
Otherwise you can use a object where you can specify the image name
var obj = {
hello: "hello.jpg",
facebook: 'facebook.jpg',
hi: 'hi.jpg'
}
var anu = document.getElementById("display");
var a = document.getElementById("final_span").textContent;
if (a.search("hello") || a.search("facebook")) {
var lb = linebreak(interim_transcript);
if (obj[lb]) {
anu.innerHTML = '<img src="' + obj[lb] + '">';
}
}

How could I call a JQuery function upon a button click?

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>

Select On Change not working correct

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.

Trying to set a variable using document.getElementById('').innerHTML

I am utterly new to JavaScript and am trying to self-learn a few things - so be gentle.
I am trying to set a variable using document.getElementById(' ').innerHTML but I can't get it to work - I just get "undefined" returned when I try to use this variable.
All of the examples I have seen says that this should work, but it isn't and I'm at my wits' end. Any help will be greatly appreciated.
This is the code...
<script>
var str = document.getElementById('str').innerHTML;
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str ;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
My ultimate aim is to add a number to the variable "str" using another variable; so something like...
var str = document.getElementById('str').innerHTML;
var add = 2
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str + add;
else
document.getElementById('str').innerHTML='unchecked';
}
I'm aware that I probably need to parse the str variable as an integer for this, but I've stumbled before I've even got that far.
Please help.
The value of str is determined when the page is loading (and before the element exists). I believe you want it inside calc:
function calc()
{
var span = document.getElementById('str');
var str = span.innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
span.innerHTML = str + add;
else
span.innerHTML = 'unchecked';
}
The problem is that your span is below the script and actually str is not still there. Here is an example which works http://jsfiddle.net/krasimir/2C25E/
<script>
function calc() {
var str = document.getElementById('str').innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = parseInt(str) + add;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
Also you should use parseInt to be sure that you get a Number and not a String.
if you had included the script in side the <head>tag This will work for you.
function calc() {
var str = document.getElementById('str').innerHTML;
//more code
Try this, a working version and a bit optimised:
var str = document.getElementById('str');
var chk = document.getElementById('checkbox');
var add = 2
function calc() {
chk.checked ? str.innerHTML = parseInt(str.innerHTML) + add : str.innerHTML = 6;
}
chk.onchange = function () {
calc();
};
Demo here

Categories