onclick() and multiple depending function calls - javascript

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.

Related

Changing value of JS variable depending on HTML button selected?

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>

JS function not displaying anything

I have made a function and captured the value of a textbox. On a button click, it should alert the value.
The code is:
function substitute (argument) {
var myVal=document.getElementById('myTextBox').value();
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
};
}
It is then executed using this:
<input type="button" name="Button" value="Click Me" onclick="substitute();">
But nothing happens. Please tell me where am I doing it wrong.
You have a few errors:
.value() is not a function: use .value
You don't need that semicolon at the end of the if statement
Your text box might not have the id that you're referring to: make sure that you have id="myTextBox" in the opening tag
While it won't cause any errors, your function definition lists a parameter, but you do not pass one when you call it.
Always check your browser console for errors if nothing is happening. Always.
function substitute () { // Parameter "argument" is not necessary
var myVal=document.getElementById('myTextBox').value; //.value, not .value()
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
}; // You don't need this semicolon
} // You were missing this curly brace
Demo
value is not a function, it's a property, therefore:
var myVal=document.getElementById('myTextBox').value;
As you're brand new to JS, I'll give you a piece of advice: If you want to manipulate the DOM, use jQuery.
In Your code, you are not passing any parameter to function subsititute(), But # function definition you wrote substitute(argument). Thats a big issue, and also you put there is a semi-column after if condition inside the function. No need of it
Try This..
<input type="text" id="myText" value="Hello" />
<input type="button" name="Button" value="Click Me" onclick="substitute();" />
In script part,
function subsitute()
{
var myVal=$('#myText').val();
alert(myVal);
if (myVal=='')
{
alert('Empty Textbox');
}
}
http://jsbin.com/tewudopi/1/edit
Add an ID to the button. When referencing the button, it is not ".value()", it is simply ".value".
As a side note, you should use === instead of == to compare.
function substitute() {
var myVal=document.getElementById('myTextBox');
alert(myVal.value);
if (myVal.value.length===0) {
alert('Empty Textbox');
}
}
Maybe something like the following.
<script type="text/javascript">
function substitute() {
var myVal=document.getElementById('myTextBox').value;
if (myVal.length>0) {
alert(myVal);
}
if (myVal.length==0) {
alert('Empty Textbox');
}
}
</script>
<input type="button" name="Button" value="Click Me" onclick="substitute();">
<textarea name="myTextBox" id="myTextBox"></textarea>
Fiddle demo

How to check if a field has been populated with data using a javascript function?

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

calling a function again in javascript

<!DOCTYPE html>
<html>
<head>
<title>input number</title>
</head>
<body>
enter no:1<input id="t1" type="text"><br>
<button type="button" onClick="myFunction()">submit</button>
<button type="button" onClick="myFunction()">next</button>
<div id="div1" style="color:#0000FF">
</div>
<script>
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no))
{
alert("Not Numeric");
}
else{
if(no!=1){
if(no%2==0){
no=no/2;
}
if (no%2!=0) {
no=(no*3)+1;
}
}
}
document.getElementById("div1").innerHTML = no;
}
</script>
</body>
</html>
After entering number in the text box when I press submit button it shows the following output
enter no:1
submit next
16
but when i press next button it is not showing any output.My expected output is when I press next button it shoult show the next no. by executing the logic in the myFunction() function.Helpme...
You haven't set any case for when no = 1. You have a case for when no != 1 and when no%2 != 0 both of which are false when no = 1. There isn't any increment logic in here to find the next number and return it. I think you are missing a } at the end of the no%2==0 clause.
Also I fail to see why you have two identical buttons here, next and submit do the same thing. Moreover I would advice more descriptive IDs. div1 isn't a good name for a div.
The javascript part should look like this, if the intention is to implement Collatz conjecture. http://en.wikipedia.org/wiki/Collatz_conjecture
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no)) {
alert("Not Numeric");
} else {
if(no!=1) {
if(no%2==0) {
no=no/2; // Note the division operator instead of mod
} else {
no=(no*3)+1;
}
}
}
document.getElementById("t1").value = no; // Note that we are writing to the textbox
}
There are some basic HTML issues too, in your post you are using the input tag as
<input id="t1" type="text"> use it as: <input id="t1" type="text" />
Secondly, when you submit the data to the function, you are having some value there! Maybe 1 is the value or 16, whatever. But when you are trying to resubmit, either its not allowed or your input is now an empty field. So the function is not executing further than this step:
if(no==""||isNaN(no))
Try to save the value in the form.
Try using this:
document.getElementById("t1").value = no;
Make sure that the value is captured as it was, because your code is changing the value into some other form, use a new variable for this. That would save the value from the input and again write it back to that input.
This will set the value for that text input as it was before the function. It might make the input again ready for the submit!

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

Categories

Resources