store value from button in variable using javaScript - javascript

I have two buttons and I want to store the value attribute of the button pressed into a variable called amount. The code below is clearly wrong I have two identical id's for both buttons. What should I be doing in the function to save the value attribute to the variable amount onclick?
<button type="button" id='btn' onclick='storeVar' value='1'>1</button>
<button type="button" id='btn' onclick='storeVar' value='2'>2</button>
<script>
function storeVar() {
var amount = document.getElementById('btn').getAttribute('value');
console.log(amount);
}
</script>

The attribute id must be unique in a document, use class instead. Also pass this to the function so that you can refer the current button inside the function:
function storeVar(el) {
var amount = el.getAttribute('value');
// OR: simply
// var amount = el.value;
console.log(amount);
}
<button type="button" class='btn' onclick='storeVar(this)' value='1'>1</button>
<button type="button" class='btn' onclick='storeVar(this)' value='2'>2</button>

Make sure to have unique Id's.
<button type="button" id='btn-one' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>
<script>
function storeVar(value){
let amount = value;
console.log(amount);
}
</script>

Either give a unique id for each button or completely remove id attribute. After fixing your html try the following code.
<button type="button" id='btn' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>
<script>
function storeVar(v){
let amount = v;
console.log(amount);
}
</script>

Related

How may I get the value of a button when a user clicks on it?

I have four buttons:
<button id="button-yardSize" class="btn btn-success" value="2"><h1>2</h1></button>
<button id="button-yardSize" class="btn btn-success" value="4"><h1>4</h1></button>
<button id="button-yardSize" class="btn btn-success" value="6"><h1>6</h1></button>
<button id="button-yardSize" class="btn btn-success" value="8"><h1>8</h1></button>
And I want to capture the value of the button clicked so that I may add it later with another button and add them together.
I added this for the JS:
var inputYardSize = $("#button-yardSize").on("click", function(){
$("#button-yardSize").val();
console.log(inputYardSize);
});
I read that I may need to use .attr instead, however not sure how to add a custom attribute to the buttons?
First of all, you should use a class, not an ID. IDs should be unique, and $("#button-yardSize") will only select the first button.
In the event listener you can use this to refer to the button that was clicked.
You need to assign the inputYardSize variable inside the function. .on() just returns the jQuery object you're binding the handler to, not the value from inside the function.
$(".button-yardSize").on("click", function() {
var inputYardSize = $(this).val();
console.log(inputYardSize);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-success button-yardSize" value="2"><h1>2</h1></button>
<button class="btn btn-success button-yardSize" value="4"><h1>4</h1></button>
<button class="btn btn-success button-yardSize" value="6"><h1>6</h1></button>
<button class="btn btn-success button-yardSize" value="8"><h1>8</h1></button>
EDIT: You should use ID for unique elements and class for repeating element.
So if you would replace the ID with class on the button, the code should look like this:
Remove the declaration from the beginning and instead use it to store the values inside the click function.
In this way, you will have the value of the clicked button with the specified class.
$('.button-yardSize').on('click', function(){
var inputYardSize = $(this).val();
console.log(inputYardSize);
})
The id of each element has to be unique
<button id="button-yardSize1" class="btn btn-success" value="2"><h1>2</h1></button>
<button id="button-yardSize2" class="btn btn-success" value="4"><h1>4</h1></button>
The JS function is incorrect, you need a click handler which will log the button value
$("#button-yardSize1").on("click", function(){
inputYardSize=$("#button-yardSize1").val();
console.log(inputYardSize);
});

javascript button value by id

Right now I have multiple rows from mysql printing off the following in php:
while($row=mysql_fetch_array($result)){
echo "<input id='dd".$row["id"]."' onclick='myFunctions()' type='button' value='".$row["id"]."'></form>";}
I am able to retrieve only the most recent value of button dd.
function myFunctions() {
var name = document.getElementById("dd").value;
There are multiple rows though, so how can I get the value of the specific one that was clicked?
This is what the html looks like:
<input id="dd4199" onclick="myFunctions()" value="4199" type="button">
<input id="dd4198" onclick="myFunctions()" value="4198" type="button">
<input id="dd4197" onclick="myFunctions()" value="4197" type="button">
<input id="dd4196" onclick="myFunctions()" value="4196" type="button">
As you can see when it does getElementById it always finds the 4199 because it is the most recent. How can the respective click be found. Thanks!
You have to create inputs with different ids. It’s not correct to have the same id in 2 different controls.
You can iterate and create ids dd1, dd2, etc.
Check this: Can multiple different HTML elements have the same ID if they're different elements?
function myFunctions(ele){
var element = ele.value;
alert(element);
}
<input onclick="myFunctions(this)" value="4219" type="button">
<input onclick="myFunctions(this)" value="5419" type="button">
//dont add inine function
//add a common class
<input class="getValue" value="4219" type="button">
<input class="getValue" value="5419" type="button">
//add event handler
for (var i = 0; i < getValue.length; i++) {
getValue[i].addEventListener('click', function(){
alert(this.vaue);
});
}
Try
for ($id = 0; $row = mysql_fetch_array($result); $id++) {
echo "<input id='dd_" . $id . "' onclick='select(" . $id . ")' type='button' value='".$row["id"]."'></form>";
}
Maybe generates:
<input id="dd_0" onclick="select(0)" value="4199" type="button">
<input id="dd_1" onclick="select(1)" value="4198" type="button">
<input id="dd_2" onclick="select(2)" value="4197" type="button">
<input id="dd_3" onclick="select(3)" value="4196" type="button">
Note: the id's are unique, so you can select them individually.
function select(id) {
var name = document.getElementById("dd_" + id).value;
}
Also, just a tip, your variable names should be more descriptive.
No one knows what dd means.
Good luck!
pass this as an argument so when you click button you can get value of clicked button
function myFunctions(a) {
var name = a.value;
console.log(name);
}
<input onclick="myFunctions(this)" value="4199" type="button">
<input onclick="myFunctions(this)" value="4198" type="button">
<input onclick="myFunctions(this)" value="4197" type="button">
<input onclick="myFunctions(this)" value="4196" type="button">

Display input value in a button

I have an input field and a button next to it, what i want to do is whatever i type in the input field then click on the button next to it, the result gets displayed in another button, here is what i tried so far:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
document.getElementById("btnresult").value = result;
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
https://jsfiddle.net/sheriffderek/p2LoLcv3/
I think this is what you are describing...
Some simplified markup
<div class="parent">
<input type='button' value='Add' rel='action' /><br>
<input type='text' rel='text-input' />
</div>
<ul class='button-list' rel='button-list'>
<!-- you need to put the buttons somewhere, right? -->
</ul>
jQuery was one of the tags, so I used it
// just caching some thing that will be reused (I like using rel)
var $parent = $('.parent'); // whatever - to keep some scope
var $addButton = $parent.find('[rel="action"]');
var $textInput = $parent.find('[rel="text-input"]');
var $buttonList = $('[rel="button-list"]');
$addButton.on('click', function() { // on click...
var currentInputValue = $textInput.val(); // get the value from input...
$buttonList.append('<li><button>' + currentInputValue + '</button></li>'); // append a new button...
$textInput.val(''); // clear input
});
You're almost there, you have to unhide the button you've hidden in the first place, and not set a value for a button, but rather the innerHTML property. Since a button doesn't hold a value, but displays the content between the tags as text.
I've commented my changes:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
// Changed from .value to .innerHTML
document.getElementById("btnresult").innerHTML = result;
// Changed style from to 'block'
document.getElementById("btnresult").style.display = "block"
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
In addition, there are several aspects of your code that could use improvement, I described them below:
function add_keyword() {
// No need for parentheses around the document.getElement function.
var keyword_value = document.getElementById("keyword").value;
// There's no need to place the value in a new variable, it is useful to place the element you wish to replace in a variable, since we'll be re-using it's instance.
var btn = document.getElementById("btnresult");
btn.innerHTML = keyword_value;
btn.style.display = "block"
}
EDIT: Since OP's goal was to create a new button with the content, this is an updated version that generates a new button for every new input.
function add_keyword() {
var keyword_value = document.getElementById("keyword").value;
// Create a new button element.
var btn = document.createElement("button");
// Set it's content to the keyword from the input.
btn.innerHTML = keyword_value
// Append it to the body.
document.body.appendChild(btn);
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>

trying to check the value in a button using javascript immediately the loads

I am attempting the check the value in a button using a javascript onload function on getting the value of the button I am performing a check and if the check is true let it disable a preview button using its id. This is the javascript snippet
window.onload = function() {
//var text = $(".badge").text();
var totalCheck = document.getElementById('totalcheck').value;
alert("before check");
if(totalCheck == "0.0"){
alert(totalCheck);
$('#disbtn').on('click',function() {
$(this).prop("disabled",true);
});
}
}
This is the button I am checking immediately the window loads
<button id="totalcheck" class="btn btn-default" type="button">
Total <span id="price" class="badge">0.00</span>
</button>
This is the button I am attempting to disable if the check is true
<button id="disbtn" class="one btn btn-primary" type="button">
<i class="fa fa-caret-down" aria-hidden="true"></i>
Preview </button>
the interesting thing is that the alert never pops up even before the check. Please what could be wrong
Reason for not working?
You are called the wrong element for matching with if condition . 0.00 is not a button value .its span text .so button
value is null so always return false in if
And if condition matching also wrong .The innerTEXT is 0.00 but you are matching 0.0 so it always false.
so try like this
var totalCheck = document.getElementById('price').innerHTML;
function start() {
//var text = $(".badge").text();
var totalCheck = document.getElementById('price').innerHTML;
alert("before check "+ totalCheck);
if (totalCheck.trim() == "0.00") {
alert(totalCheck);
$('#disbtn').on('click', function() {
$(this).prop("disabled", true);
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="start()">
<button id="totalcheck" class="btn btn-default" type="button">
Total <span id="price" class="badge">0.00</span>
</button>
<button id="disbtn" class="one btn btn-primary" type="button">
Preview </button>
</body>
You have to take 'price' instead of 'totalcheck' to get your totalcheck,
var totalCheck = document.getElementById('price').innerHTML;
The value Total is contained inside your span with ID "price".
Use innerHTML in place of value, since span does not support the property value.
var totalCheck = document.getElementById('price').innerHTML;

jQuery - Cant get attribute of appended element

I am trying to get the ID-attribute of an element that I have appended into my HTML. However, all I get is 'undefined'. How can I solve this?
jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction();" />');
function myFunction (){
alert(jQuery(this).attr("id"));
}
$('body').find('input[class="button"]').attr('id')
or try to pass the id as parameter of the function
...append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this.id);" />');
function myFunction(id){
alert(id)
}
you can pass 'this' in function parameter and in the function definition you will get whole input tag
jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this)" />');
function myFunction(e){
$(e).attr('id')
}

Categories