Calling a variable in javascript using a button - javascript

I want to make a function and call that function on the click of a button. There are many guides on the internet to do this but it just didn't work. (I'm a beginner)
<script type = "javascript/text">
var name = function()
name = prompt ("Who are you?", "");
alert ("hello" + " " + name);
</script>
How do i call "name"?

I changed your code into this:
<script>
var name = prompt ("Who are you?", "");
alert ("hello" + " " + name);
</script>
This should work. You don't even need a function here.
But if you want to store a function in a variable and then call it, just do:
var myFunction = function() {
// function body
}
myFunction(); // calling it!

Related

How can I access variable from a concatenated script that holds another script inside it?

I have this code to open a file in NW.JS.
function chooseFile(name, handleFile) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
for(var f of this.files){
console.log(f.name);
console.log(f.path);
handleFile(f.name, f.path);
}
}, false);
chooser.click();
}
chooseFile('#fileDialog', function(name, path){ ... /* do something with the file(s) */ });
I have concatenated that code into a string so that I can inject it into a div (when that div is created) from a button click that generates the above code with unique id’s thusly..
var letsDoThis = '$(".' + imgUploadClass + '").click(function(){ var leid = this.id; var theEditId = "divId" + leid.slice(5); function ' + imgUploadChoose + '(name, handleFile) { var chooser = document.querySelector(name);chooser.addEventListener("change", function(evt) { for(var f of this.files){console.log(f.name);console.log(f.path);handleFile(f.name, f.path);}}, false);chooser.click();}' + imgUploadChoose + '("#' + imgUploadzz +'", function(name, path){' + 'alert(path);' + ';});});';
When testing I can access the name and path inside the alert box! GREAT! The code I want to run where
'alert("Hello!");’
is needs to be the following (but instead of a hardcoded url I need to access “path” from the (uniquely named) chooseFile script)...
'$("#" +' + 'theEditId).css("background-image", "url(http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg)");'
I am pretty sure I am not escaping a comma or something, here is another piece of code I got to fire correctly but not being able to access “path”...
'$("#" +' + 'theEditId).css("background-color", "green");'

Javascript url content with parameter?

I wish to pass 'selectlang' parameter in javascript and redirect to the MVC controller but the var 'selectlang' have error and mention that it does not exist in current content? Please guide me thanks!
My javascript:
$('.filterlang').on("click", function () {
var selectlang = document.getElementById("Language").value;
location.href = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=" + selectlang)';
});
filterlang is button class and "Language" is dropdownlist id.
Have you tried this:
$(document).on(".filterLang", "click", function(){
var selectedLang = $("#Language").val(); // if it is normal dropdown, this will work for both cases
var selected2Lang = $("#Language").select2("val"); // if it is select2 dropdown
window.location = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=' + selectlang + '")';
});
Hope this helps.

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

Call JS function after paste keyboard shortcut?

I'm trying to write a simple script that will take a list of urls that I need to save, append them to an array, and then spit that array back out in a div. The problem I'm having is that I am using ".onKeyUp" to call the function. It works, but when I use ctrl + v to paste, the function gets called twice. Once when you release the letter v and once when you release control. How can I fix it so that it will only call the function once when I'm using the keyboard shortcut? Here is my code:
<script type="text/javascript">
var arr = new Array();
function procession() {
var urlin = document.getElementById('url').value;
var smacky = "<br/> the url is: " + urlin + "<br/> the url is: www." + urlin;
arr.push(smacky);
document.getElementById('list').innerHTML = arr;
}
</script>
<form>
<input onkeyup="procession();" type="text" size="50" id="url"/>
</form>
<div id="list"></div>
Important Note: It's a long story, but I can't use jQuery for this script. Is there a way to do it in just pure javascript?
Pass in event to your onKeyUp, if the key is a ctrl, return false. This will only register one keyup event for shortcuts now:
<input onkeyup="procession(event);" type="text" size="50" id="url"/>
JS:
function procession(e) {
//if ctrl key, return false
if (e.which == 17) return false;
//do stuff
var urlin = document.getElementById('url').value;
var smacky = "<br/> the url is: " + urlin + "<br/> the url is: www." + urlin;
arr.push(smacky);
document.getElementById('list').innerHTML = arr;
}
It's a little hack-ish, but it should get the job done.
Here:
$(document).on("paste", function(event) {
alert("paste!");
});

.val() not getting updated value from input

I have two input fields, and I'm trying to get their values using jquery by clicking a button. It seems like a very simple operation, but for the life of me I can't get it to work. Here is the code snippet:
Name: <input type="text" id="name" value="test1"><br>
Message: <input type="text" id="line" value="test2"><br>
<button id="submitButton">Submit</button>
<script>
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
</script>
If I don't specify the value, the alert returns with undefined for both variables. If I change the values of the input and click the button, it still says test1 and test2. There has to be something simple that I'm missing here, anyone know what it is?
In your code, you fetch the values when the script is initialized, and then reference the value they had at that point in your click function rather than fetching the current value.
Try:
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});
name1 = $("#name").val()
creates a new string variable name1 that has the value of $("#name").val() as it is at the moment. .val() does not get called each time you try to access name1. The simplest thing to do would just be to use $("#name").val() instead.
http://jsfiddle.net/wTvku/
As mentioned in other answers, the problem is that you are precomuting the variables and expecting them to magically change. However I would strongly suggest using Vanilla JS
document.getElementById('submitButton').onclick = function() {
var name1 = document.getElementById('name').value,
line1 = document.getElementById('line').value;
alert("Name: " + name1 + "\nMessage: " + line1);
};
you should wrap your code within document.ready() event...
$(document).ready(function() {
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
// Handler for .ready() called.
});
You've set variable values outside of the click function. To the value is set on page load, not whenever you run the function. Try this:
Name: <input type="text" id="name" value="test1"><br>
Message:
Submit
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});

Categories

Resources