How to get value from input field with Javascript? - javascript

How can I get the value of an specific input field with Javascript?
Lets take this shopify shop for example: https://geekymate.com/products/magic-doormat-1?variant=18941211607138
I am trying to create a script which is automatically applying an discount code based on the quantity filled in the quantity field.
But to do that I need to be able to get the latest value of the field.
How would the code look like to get the latest/current value?
EDIT: Thank you for the hint with the question. I do know that I need to use getElementById ( For the linked page above it would be this: var x = document.getElementById("Quanity").value; ) but how do I always get the latest input automatically if the enduser is changing the value?

The other answers are also correct (using jQuery .keyup), but you can also use this solution below (which is better). This solution uses pure javascript.
The code selects the element by using .getElementById() and uses .addEventListener() to do something when input changes.
var text = document.getElementById("text");
window.onload = function() {
text.addEventListener("input", function() {
console.log(text.value);
});
}
<input id="text" />
Or you can use the following if you want a jQuery solution. This uses jQuery .bind().
$("#text").bind("input", function() {
console.log($("#text").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="text" />

keyup() function ;)
It runs each time, when user types new text.
Also, you can use input() or change() functions.
In jQuery it works like this:
$(document).on('keyup', '#InputID', function(){
//...code...
var discount = Number( document.getElementById('InputID').value )*10/100;
});

It's a Jquery function that runs on keypress. I've included a snippet below to see how it would tie in with an input field.
$('#code').keyup(function() {
var discountcode = this.value;
console.log(discountcode);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="code" type="test" />
Keyup runs every time a specific element is lifted. Imagine someone enters 'Hello'
You will see the following logged:
'H' 'He' 'Hel' 'Hell' 'Hello'

look at the code snippet. using JavaScript to get the values. and can use addEventListener to detect the change and use detectChange function to get the latest values.
var discount = [];
function detectChange() {
var table = document.getElementsByClassName("shappify_qb_grid")[0];
for (var i = 0; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
row = table.rows[i].cells[j].innerHTML;
rate = parseFloat(row);
if (rate && discount.indexOf(rate) < 0) {
discount.push(parseFloat(row));
console.log('---', parseFloat(row));
}
}
// console.log('discount : ', discount);
}
}
}
detectChange();
console.log('discount : ', discount);
<table class="shappify_qb_grid" border=1>
<thead>
<tr>
<th>Qty</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Buy 1</td>
<td>0% Off</td>
</tr>
<tr>
<td>Buy 2</td>
<td>10% Off</td>
</tr>
<tr>
<td>Buy 4</td>
<td>12% Off</td>
</tr>
<tr>
<td>Buy 5</td>
<td>14% Off</td>
</tr>
<tr>
<td>Buy 6</td>
<td>17% Off</td>
</tr>
</tbody>
</table>

This work for me!
document.getElementById("text").value;
<input id="text" />

Use the document.getElementById(); -command to get the existence of the referenced element in your HTML page. Then use the same technique of assigning attributes in the original HTML coding rules.
Use document.getElementById('able').value = 'whatever';.

Related

Onchange on a lot of inputs JS vanilla

I have multiple inputs on my website.
The inputs created with createElement.
I can give every input class, id and etc.
My goal: every time the user inserts new input (amount of products) it will calculate the overall price without any click, just automatic calculation(object price * amount in the input).
I would post the code, but I think image will explain it better:
How can I do the onchagne with getElementByTagName.
Example will be grate. Thank you !
You can use event delegation. Several events -- like "change" -- on your input elements will bubble up to container elements, up to the root of the DOM. So identify which is the common ancestor element, and listen there for the event you are interested in. I will choose the "input" event, as it triggers on any change the user makes, via any way of input:
document.addEventListener("input", function() {
// make calculation here:
});
This way you only need to attach one listener.
You can do something like this
function changeHandler() {
// on change handler
}
const inputs = [...document.getElementsByTagName('input')];
inputs.forEach(input => input.addEventListener('click', changeHandler));
You can do this with classes, which is better than applying your job to all your inputs.
I hope is something like this do you need :
function addInputListener(input) {
//#todo Replace this by your data
let row = input.parentElement.parentElement;
let overallPriceElement = row.querySelector('.overall-price');
let price = parseInt(row.querySelector('.price').innerText);
let calcEvent = function() {
//#todo Put your calc function here
if (this.value > 0) {
overallPriceElement.innerText = (price * this.value).toString();
} else {
overallPriceElement.innerText = "No products yet";
}
};
input.addEventListener('input', calcEvent);
calcEvent.call(input); // call() is here to add input context
}
// It's better to use class instead tag to do your job
let inputs = document.querySelectorAll('.amount');
// But you can also use tag do this
//let inputs = document.querySelectorAll('input');
for (let i = 0; i < inputs.length; i++) {
let input = inputs[i];
addInputListener(input);
}
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>Amount</th>
<th>Overall Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Bread</td>
<td class="price">3</td>
<td><input type="number" class="amount"></td>
<td class="overall-price"></td>
</tr>
<tr>
<td>2</td>
<td>Bread</td>
<td class="price">10</td>
<td><input type="number" class="amount"></td>
<td class="overall-price"></td>
</tr>
<tr>
<td>3</td>
<td>Bread</td>
<td class="price">30</td>
<td><input type="number" class="amount"></td>
<td class="overall-price"></td>
</tr>
</tbody>
</table>
You can call function addInputListener(input) each time you create new row pass directly your new input created by createElement to add these listeners.

Append data on button click

Hi StackOverflow people,
I have a question regarding a small web application that I am currently building.
I have a table of data, in this case phone numbers. I want to apply the phone number when the user clicks on a button next to the number in the table.
User clicks on a phone number in table.
Phone number gets added/appended to input field .
Any help is greatly appreciated!
Kind regards, Casper.
Try below code for the same :
$('#buttonId').click(function(){
$('#inputId').val($('#pnonumberId').val());
});
I think you are looking for something like this, let me know if anything else you are asking for.
Sample html assuming I understood the problem right:
<table>
<tr>
<td>1234567890</td><td><button class="btn">Select this</button></td>
</tr>
<tr>
<td>1111222233</td><td><button class="btn">Select this</button></td>
</tr>
<tr>
<td>2255667788</td><td><button class="btn">Select this</button></td>
</tr>
</table>
<input type="text" class="phone" />
Now for the javascript, something like the following should work:
var btns = document.querySelectorAll('.btn'),
phone = document.querySelector('.phone');
// looping through the nodelist and attaching eventlisteners
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function(event) {
// fetching the phone number
var selectedPhone = event.target.parentNode.previousSibling.textContent;
phone.value = selectedPhone; //setting the value
}, false);
});
Created a fiddle and tested. Link to fiddle: http://jsfiddle.net/subhamsaha1004/4f5cX/
Hope this helps.
If the number of rows in the table is more attaching event listeners to every button might not be good idea. The javascript should be changed to attach the listener to the table instead like this:
var table = document.querySelector('table'),
phone = document.querySelector('.phone');
table.addEventListener('click', function(event) {
// fetching the phone number
if(event.target.nodeName.toUpperCase() === 'BUTTON') {
var selectedPhone = event.target.parentNode.previousSibling.textContent;
phone.value = selectedPhone; //setting the value
}
}, false);
$('.phoneNumer').on('click', function(){
$('#input').attr('value', 'valueToshowInInput');
});
Something like this? You need jQuery for this.
fiddle here: http://jsfiddle.net/JbB4U/
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<input type="text" value="" id="phone">
<table id="phone-list">
<tr>
<td><span class="phone-number">1XXXX-YYYYY</span><button class="click-number">Phone1</button></td>
</tr>
<tr>
<td><span class="phone-number">2XXXX-YYYYY</span><button class="click-number">Phone2</button></td>
</tr>
<tr>
<td><span class="phone-number">3XXXX-YYYYY</span><button class="click-number">Phone3</button></td>
</tr>
</table>
<script>
$(document).ready(function(){
var $phoneEdit = $("#phone");
$("#phone-list .click-number").click(function(){
$phoneEdit.val($(this).prev("span.phone-number").html());
});
});
</script>
Give an ID to the text field and also to the div section where the phone number is, Then use this jQuery code
$("#phone-list span.phone-number").click(function(){
$( "#phone" ).append($(this).val());
});

Is it possible to get the value of a <td> element using onclick?

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')

Get <table> element's nth <td> innerHTML dynamically

Is there anyway I can get the innerHTML of the designated nth <td> in a <table> using JavaSCript?
Since my table is automatically generated, my <td>'s do not have IDs. I am using the following HTML code:
<table id="table">
<tr>
<td onmouseover="myTD()">Cell 1</td>
<td onmouseover="myTD()">Cell 2</td>
<td onmouseover="myTD()">Cell 3</td
</tr>
<tr>
<td onmouseover="myTD()">Cell 4</td>
<td onmouseover="myTD()">Cell 5</td>
<td onmouseover="myTD()">Cell 6</td>
</tr>
</table>
But how do access, for instance, Cell 5?
Thanks a lot!
var cells = document.getElementById('table').getElementsByTagName('td');
This will contain all your table cells. Use array notation to access a specific one:
cells[4]
Here's a quick demo which changes the background color:
http://jsfiddle.net/jackwanders/W7RAu/
Not sure what you want - Dom: document.getElementsByTagName("table")[0].rows[2].cells[1]
Pass the cell back to the function:
<td onmouseover="myTD(this)">Cell 1</td>
Get the innerhtml from the object:
function myTD(obj) {
alert(obj.innerHTML);
}
Can you clarify when (on load, on hovering, ...) and where (client side, server side ...) you want to do that?
If you need the cell inside myTD, just use the this keyword, which happens to be your HTMLTableCell:
function myTD() {
this.style.color="red"; // just for the example, using CSS classes is much better
}
Using just CSS you could do:
#table tr:nth-child(2) td:nth-child(2)
{
background:#ff0000;
}​
jsFiddle example
function addClassToNthTD(n) {
var table = document.getElementById('table');
for (var i = 0; i < table.childNodes.length; i++;) {
var rows = table.childNodes[i];
for (var j = 0; j < tr.childNodes.length; j++;) {
n = n - 1;
if (n == 0) {
tr.childNodes[j].className = 'foo';
}
}
}
}
This line:
$('td')
Places all of the td elements in the code into a zero-based array, so the cell with 'Cell 5' as its content would be the fifth element of that array, ie:
$('td')[4]
jQuery also accepts CSS style selectors, so if you wanted to target the every second cell in a row, you could use a selector such as:
$('tr td:nth-child(2)')
Read through the selector documentation I've linked, it can come in very handy for situations like this
I have no idea what you are trying to do, but if you want to do some kind of "hover" ability, jquery can do that quite simple. i have created an example Fiddle http://jsfiddle.net/fd3GK/1/

How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery

<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>
Goal: To get buttons button1 and button2 to trigger the same function get() which should get the value of the first <td> in the same <tr> the button resides in. Which is, in this case: foo1 and foo2 respectively.
This is a rough outline of the function which should help understand what I'm trying to achieve-
function get(element){
alert(element.tr.first_td.innerHTML);
}
I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.
Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:
function find( element ) {
alert( element.parentNode.parentNode.cells[0].innerHTML );
}​
Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/
Try this, since you have many tr and td tags right, so, you can do DOM Parsing. But you need to specify one ID for the table to get that table. For now lets call it foo-table.
var table = document.getElementById("foo-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
If you don't wanna give an ID and you are sure that there is only one table, then use this:
var table = document.getElementsByTagName("table");
var cells = table[0].getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
Enjoy! Hope this helps! :) No jQuery or any other plugin. Pure JavaScript. :)
<table>
<tr>
<td id="button1_value">foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get('button1_value');"></td>
</tr>
<tr>
<td id="button2_value">foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get('button2_value');"></td>
</tr>
</table>
You shoul identify what you want to get using an ID so that you can easily retrieve it. This also helps prevent the chance of getting erroneous data. If you give the component an id you should be able to use document.getElementById() to get that component.
function get(element){
var obj = document.getElementById(element)
alert(obj.innerHTML);
}

Categories

Resources