How to identify which button was pressed in javascript? - javascript

How to identify which button was pressed in javascript
in have 4 buttons that present items and text box
when i press a buttons, the number in the text box add to sum

We would really like to help you but you should provide some more information how you would like to realize that and what your actual code looks like.
Did you say that you are trying to realize a calculator? There are many ways how to identify the button which was triggered, e.g. pressed. In the example you provided above (Calculator) a javascript function is called if the user clicks on a specific button. To achieve that, the function call is made within the onClick event:
<INPUT type="button" name="one" value="1" OnClick="btnPressed(1)">
The called function could look like this:
function btnPressed(value){
var obj = document.getElementById('ID_of_textbox')
obj.value = parseInt(obj.value) + value
}
If you would like to identify which button was clicked, you can do it with the numbers stored in the 'value' argument. Or on the other hand you could change the trigger to:
<INPUT type="button" name="one" value="1" OnClick="btnPressed(1, this)">
and the JS function to:
function btnPressed(value, sender){
...
}
If you are willing to use the 'this' reference like illustrated above, then you can also do a step further and change the whole thing to something like this:
<INPUT type="button" name="one" value="1" OnClick="btnPressed(this)">
function btnPressed(sender){
var obj = document.getElementById('ID_of_textbox')
obj.value = parseInt(obj.value) + parseInt(sender.value)
}
You can also do it directly in the onClick of the INPUT:
<INPUT type="button" value="1" OnClick="document.getElementById('ID_of_textbox').value = parseInt(document.getElementById('ID_of_textbox').value) + 1">
or:
<INPUT type="button" value="1" OnClick="document.getElementById('ID_of_textbox').value = parseInt(document.getElementById('ID_of_textbox').value) + parseInt(this.value)">

Related

Radio option on view that updates and changes view?

I think that my problem isn't very hard -but I'm pretty new to this and having issues finding an easy solution.
I have a form that collects a few items, and an output page that creates a table based on those few items. For example, one of the form options is "Which leg is affected?" And you must choose either "Left, Right, Both".
I would like to create a radio selection option on the view so that the person using this tool won't have to click the back button to update this one field. The table that is built changes based on this one selection, so it would be nice to see those changes without resubmitting the form.
If anyone can point me in the right direction - either JavaScript or some method that involves re-sending the form values from the view - I would be very grateful.
I believe what you're describing is exactly what the idea of "single page app" style coding with Javascript is for - modifying the page with logic without necessarily needing to make a server request. I.e., you want to make an "application." Albeit a simple one.
What I recommend you look into is "event handlers," specifically the click handler.
So, if you had html that looked like: (stolen from MDN's radio page)
<form id="radio_form">
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1"
name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2"
name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3"
name="contact" value="mail">
<label for="contactChoice3">Mail</label>
</div>
</form>
You could then have code that looked like
var radio = document.getElementById('radio_form');
radio.onclick = changeTable;
function changeTable(e){
// Do logic here to change table
}
The idea is your page is "waiting" for the form to be "clicked" (you could also look into onChange), and when it is clicked, a function is invoked that does further logic.
See here to figure out how to get the value of a selected radio.
See here for using javascript to insert a row into a table (what you may want to do in your changeTable function).
EDIT: One "gotcha" to look out for is if your script is running when the page is actually loaded. This can be a problem if your page loads asynchronously (doubtful). Just in case, also look into some kind of document.ready implementation: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
You can add an event listener for 'click' to each radio input and have the callback function modify the view in whatever way you want.
Here's an example:
const form = document.querySelector('.choice-form');
const display = document.querySelector('.display');
form.querySelectorAll('input[type="radio"]').forEach(input => {
input.addEventListener('click', () => {
display.innerHTML = "";
if (input.id === '1') {
display.innerHTML = "<span>You selected: <span class='red'>One</span></span>";
} else if (input.id === '2') {
display.innerHTML = "<span>You selected: <span class='blue'>Two</span></span>";
}
});
});
.red {
color: red;
}
.blue {
color: blue;
}
<div>
<form class='choice-form'>
<label for='choice'>Make a choice</label>
<input type='radio' id='1' name='choice'/>
<label for='1'>One</label>
<input type='radio' id='2' name='choice'/>
<label for='2'>Two</label>
</form>
<div class='display'>
</div>
</div>

How to create an HTML <input> submit button that saves all data to JS variables?

I know I can create several types of options, questions, checkboxes, and buttons using in HTML. How can I save the response a user enters and assign it to a variable? Here's the code I'm using right now:
HTML:
<input type="text" value="Hotel Name" id="questionOne"><h1 display="block">WHAT IS THE NAME OF THE HOTEL</h1><br>
<input type="button" value="HELLO" onclick="testFunction()">
JS:
function testFunction() {
prompt(document.getElementById("questionOne").value;);
}
Shouldn't it activate the function when the HELLO button is clicked, and then it identifies the response through the ID "questionOne" and creates a prompt with the variablev value? I don't understand why it's not working.
I'm new to JS and HTML so please don't go crazy if it's a simple answer. Thank you.
I think your problem is to do with where things are defined. Rather than using onclick, add an event listener in your js. e.g.
document.getElementById ("bar").addEventListener ("click", foo);
function foo() {
prompt(document.getElementById("questionOne").value);
}
and just change the button to have an id and get rid of the onclick:
<input type="button" id="bar" value="HELLO">
Well you can just add event Listener to your input.
Like
document.getElementById('questionOne').addEventListener('input',function(){
var somevariable = prompt(this.value,'');
});
That will save the answer of prompt to 'somevariable'.

How to get the onclick button to replace the function values instead of adding them

I've created a simple adding calculator within an HTML form to get to know javascript a bit better. The javascript looks like this -
function add() {
var x = document.getElementById("numberOne").value;
var y = document.getElementById("numberTwo").value;
return parseInt(x) + parseInt(y);
}
The HTML -
<form>
<input id="numberOne" type="number"/></br>
<input id="numberTwo" type="number"/></br>
<input type="button" value="Calculate"
onclick="document.body.appendChild(document.createTextNode(add()));"/>
</form>
Now, upon clicking the button, what happens is it just adds the values as a straight line. For instance, if I enter 5 and 5 and click Calculate 3 times I get 101010 instead of 10 three separate times.
I'd like for it to either replace the output or alternatively display it on a separate line and not as a straight line.
You can create a separate result div and then overwrite it each time:
<form>
<input id="numberOne" type="number"><br>
<input id="numberTwo" type="number"><br>
<div id="result"></div>
<input type="button" value="Calculate"
onclick="document.getElementById('result').innerText = add();">
</form>
Mehuls answer is correct, but...
Don't apply action inside onclick attribute, You should handle it with event listener
Assign result element to variable, so Your script will not search
for this element in whole DOM tree every time You click the button
Use textContent instead of innerText because innerText will cause browser reflows

Pass Checkboxes values to JavaScript

I am declaring 5 checkbox values in myform with the name as "yourname". On clicking submit button javascript function will be called.
In the JS function, I need to pass this value into parent window.
MyHTML Code is:
<input type="checkbox" name="yourname" value="ankit">Ankit<br/>
<input type="checkbox" name="yourname" value="rahul">Rahul<br/>
.. and more
<input type=button value='Submit' onclick="post_value();">
For Example, Using Below JS Code will print all values to the parent window.
function post_value(){
var yourname = ["ankit","rahul","vipin","abhishek"];
alert(yourname);
opener.document.f1.p_name.value = yourname;
self.close();
}
Kindly Help,
Give id to all your checkboxes and Check which one is checked using
document.getElementById('checkBoxId').checked
This will return you true/false.

I need to perform an action based on which radio button is selected (by jQuery), but neither jQuery's click or change method is doing what I want

In the callback of a HttpRequest I have, I run this jQuery code:
$("input[value='"+data.notetype+"']").click();
So the radio button with the value of data.notetype is selected. This works fine. But I need to perform an action based on what button is now selected.
If I use the change() method like this
$("input[name='note_type']").change(function () {
var clicked = $("input[name='note_type']:checked").val()
alert(clicked);
});
it works fine when I click on the radio buttons, but when the radio button is set by the first line of code above, nothing happens.
If I use the click() method like this
$("input[name='note_type']").change(function () {
var clicked = $("input[name='note_type']:checked").val()
alert(clicked);
});
it works fine when I click on the radio buttons, but when the radio button is set by the first line of code above, the message box shows the value of the radio button that was selected, not the one it is changing to.
Can anyone let me know how to fix this problem? Thanks for reading.
$("input[name='note_type']").click(function () {
var clicked = $(this).val();
alert(clicked);
});
Here is a solution for this problem, I think this will help you
For example following is your html
<input type="radio" name="some_name" value="1"> 1 <br />
<input type="radio" name="some_name" value="2"> 2 <br />
<input type="radio" name="some_name" value="3"> 3 <br />
<input type="radio" name="some_name" value="4"> 4 <br />
Try following jquery for this html
$('input[type=radio]').bind('click', function() { alert( $(this).val() ); });
I hope this will help

Categories