Hi guys so i am trying to change the value of a javascript variable depending on what button is selected. For example
<button id="1" onclick="changeVal('val1')">b1</button>
<button id="2" onclick="changeVal('val2')">b2</button>
<script>
var value;
function changeVal(choice) {
if (choice == 'val1') {
value = 'number value 1'
} else if (choice == 'val2'){
value ='number value 2'
}
*etc for more buttons*
}
</script>
The variable value will then be used later on.
Can't really wrap my head around the problem, im either doing it completely wrong or so close but can't quite get there.
edit:
So still having trouble, basically i want to return that choice value so it can then be called in another function e.g.
<script>
var value...
function changeval... //Return choice value out
function useValue() {
alert(choice) //Use choice value here
}
note ignore syntax wrote quickly.
The above code runs perfectly in a web browser. The problem must be with the concept of variable scope. Or in the function you are using the value variable.
Please consider assigning the "choice" variable to a global variable, so that it can be accessed outside the function.
Sample snippet is as follows:
<button id="1" onclick="changeVal('val1')">b1</button>
<button id="2" onclick="changeVal('val2')">b2</button>
<button id="3" onclick="display()">Display Value</button>
<script>
var value = "";
var globalChoice ="";
function changeVal(choice) {
if (choice == 'val1') {
value = 'number value 1';
} else if (choice == 'val2'){
value ='number value 2';
}
globalChoice = choice;
}
function display(){
alert(globalChoice);
}
</script>
Related
I am very new to JavaScript programming, and i am trying to do form validation using JavaScript.
While learning form validation i was reading about how to disable submit button until all input fields are validated, i saw many techniques to do this, but, i am confused regarding the following code:
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage(this)" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var bt = document.getElementById('btSubmit');
if (txt.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here this is passed as an argument from an input element event listener in html. I tried passing something other than this from there, it didn't work only passing this works,
As far as i know this in JavaScript signifies current-execution-context, but since this is JavaScript keyword then how it is interpreted inside html?
JS FIDDLE LINK while passing 'this': https://jsfiddle.net/s0vnjpqb/
JS FIDDLE LINK while passing 'some': https://jsfiddle.net/s0vnjpqb/
PS: I am new to JavaScript, hence the question is easy, this might not match the standards of stack-overflow, but i tried researching in stack-overflow as well as on other platform i couldn't understand it.
As you mentioned correctly in the description that this in Javascript signifies the current execution context.
Similarly in html
this also represent the value of the ThisBinding of the current execution context and this.value indicates the value of the current execution context
e.g txt.value in your case.
Alternately what you can do is,
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage()" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var value = document.getElementById("txt").value;
var bt = document.getElementById('btSubmit');
if (value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
This code is what i got so far:
<html>
<head>
<script>
function confirmer(what) {
var retVal = confirm("Do you want "+what+"?");
if( retVal == true ) {
document.write ("User wants "+what);
return true;
} else {return false;}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmer('a'); confirmer('b'); confirmer('c')" value="Result">
</form>
The user should be able to choose between a, b or c. Sometimes it's only a and b (the confirmer-functions-calls are written with PHP dynamically).
The problem is: Even if the user chooses an option it calls the following function but it should break/stop/end and not asking for another confirm.
You can simplify your code a bit so that you only have to make a single function call. You can achieve this by hard-coding your options into your function, instead of hard-coding them in the inline HTML. For example:
function confirmer() {
console.clear();
var options = ['a', 'b', 'c'];
var option;
while (options.length) {
option = options.shift();
if (confirm(`Do you want ${option}?`)) {
console.log(`User wants ${option}`);
return true;
}
}
console.log('User does not want any option');
return false;
}
<input type="button" onclick="confirmer()" value="Result">
You need to check the result of each method call in order to decide if you should move on to the next one.
The following is a version of your code that will do just this.
<input type="button" onclick="if (!confirmer('a')) { if (!confirmer('b')) { confirmer('c'); } }" value="Result">
If you cannot modify the output from the PHP, then you can use a global variable to prevent the other confirmations from executing.
var confirmed = false; // global variable
function confirmer(what) {
if (!confirmed) {
var confirmed = confirm("Do you want "+what+"?");
if (confirmed) {
document.write ("User wants "+what);
}
}
}
Though this would require you to reset that global variable in order to run the code again without a page refresh. So your input might look something like this:
<input type="button" onclick="confirmer('a'); confirmer('b'); confirmer('c'); confirmed=false;" value="Result">
Notice that confirmed=false; was added at the end of the code generated by PHP.
I'm trying to make js detect whats in a input box, and if the user typed in a code, something will happen so far I got this
function input() {
document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
<input id="hehe" type="text" oninput="input()">
but it's not working for some reason and I can't see why
you have to save the value before you can use it. document.getElementById('hehe').value RETURNS the value of the input textfield but in the next line you're using the non existing variable value.
just change it to:
function input() {
var value = document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
or use it directly:
function input() {
if (document.getElementById('hehe').value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
You are not assigning the DOM element value to a variable. You should write:
var value = document.getElementById('hehe').value;
Or, using jQuery:
var value = $('#hehe').val();
However, another automated way to detect entered text, using KnockoutJS library, is data-bind. It automatically synchronizes the DOM element with your Model after applying the binding to your ModelView.
Here is an example: (jsfiddle)
HTML:
<p>Name: <input data-bind="textInput: name"></p>
<h1>The typed name is: <span data-bind="text: name"></span>.</h1>
JavaScript:
ko.applyBindings({
name: ko.observable("SOMETHING")
});
Use onkeypress instead of oninput.
http://jsfiddle.net/VDd6C/8/
I have written the script below with some help. I am now trying to combine with an IF Statement. Here is what I am trying to accomplish, if %%GLOBAL_Availability%%is empty, then do not display the button. Else, display the button and run the script.
I did some research and came up with the below:
if (%%GLOBAL_Availability%% ==""){
<div><input id="ShopButton" style="display: none";></div>
}
else {
<!--Amazon Shopping button-->
<div><input id="ShopButton" </div>
<script>
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
</script>
}
It did not work at all. I am VB.net, and just learning this hard way.
Any suggestions?
Thanks.
I'm assuming that your variable %%GLOBAL_AVAILABILITY%% is a string since you're testing that it's empty via testing that it's equal to a blank string.
In javascript I'd offer 2 tips for testing if a string exists or is empty.
1 - use the .length property of the String object.
2 - to check that it exists check that the type of %%GLOBAL_AVAILABILITY%% is a string use the identity operator === to check that the variable is of type string.
Your if statement should look like the below:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
//execute code
}
Secondly, javascript is made to manipulate the DOM, so there's no need to insert new HTML based on a condition, you can just manipulate the properties of the existing HTML - in this case, setting the display property of '#ShopButton' to none.This can be achieved like this:
document.getElementById('ShopButton').style.display = "none";
So, your code should look like this:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
document.getElementById('ShopButton').style.display = "none";
} else{
document.getElementById('ShopButton').style.display = ""; //MAKE VISIBLE
document.getQuerySelector('#ShopButton').addEventListener('click', function(){
document.location.href = '%%GLOBAL_AVAILABILITY%%';
});
}
It seems you want the input to be "display: none;" if the variable is empty, in which case you can just change the style attribute based on the variable. Something like:
<div><input id="ShopButton" style="display: none";></div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
This will simply render the element as invisible and then the script will make it visible if the variable isn't empty.
<div>
<input id="ShopButton" style="display: none";>
</div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
Is this what you're trying to do maybe?
Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});