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());
});
Related
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';.
I need to write HTML and Javascript code inline i.e. inside HTML Body (Need to display some random whole number value) I sought a lot of blogs but found no help so far in doing so. Please advise.
I wanna achieve this functionality:
<td class="vhead">Offered Calls</td>
<td>
<script>
Math.random();
</script>
</td>
</td>
Try this
<td id="demo"></td>
<script>
document.getElementById("demo").innerHTML = Math.random();
</script>
for the most simple case
<td class="vhead">Offered Calls</td>
<td>
<script>
document.write(Math.random());
</script>
</td>
Javascript does not work like this. It can with the help of templating libraries. Instead you will need to get a reference to the place in html you want to inject this random value. The below assumes you will have many and want a different random number in each.
<td class="vhead">Offered Calls</td>
<td class="random"></td>
<script>
window.document.onload = function(){
var elements = document.getElementsByClassName('random');
[].forEach.call(elements, function (el) { el.innerHTML( Math.random() ) });
}
</script>
Below you'll find a simplified example of the code I am using and what I am trying to accomplish.
I'm tracking multiple variables with jQuery that need to call a function on a certain event. The problem is that I don't manage to use only that variable that just changed.
In the HTML body section I have a couple of input fields where people can fill in a number. That number should be formatted with commas as a thousand seperator. Thanks to Elias Zamaria I found an good solution for this (https://stackoverflow.com/a/2901298/7327579). Now I want this implemented with jQuery so I can track all of my variables that will get number inputs at once.
<html>
<title></title>
<head>
In the head of the html I insert my script to track my variables:
<script language="javascript">
var Currency = function() {
this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);
The function that formats the numbers and should only get the current number from the current variable that is being changed:
this.formatCurrency = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
};
};
Tracking starts and on the keyUp event my function is called. Only the current variable should be a parameter of the called function.
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
currency.formatCurrency(this);
});
});
</script>
</head>
Here below are the concerning input fields in my form:
<body>
<form>
<table>
<tr>
<td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
</tr>
<tr>
<td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
</tr>
<tr>
<td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
</tr>
<tr>
<td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
</tr>
</table>
</form>
</body>
</html>
How can I make sure that that the function only applies to the current element that caused the event?
In a jQuery event handler, this refers to the element that the event was triggered on. And you need to use .value to get the value of an input. So you should write:
$(document).ready(function() {
var currency = new Currency();
currency.currencyType.keyup(function() {
this.value = currency.formatCurrency(this.value);
});
});
<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);
}
I have a set of search results presented in a table. Each row has a radio box. Once the user has selected a row I would like to access the description text from the neighboring cell.
Using jQuery or straight javascript, what is the best way to do this?
<tr class="odd">
<td class="chosenCode"><input type="radio" value="123" name="chosenCode"></td>
<td class="codeFound">123</td>
<td class="descriptionFound">This is description text for code 123</td>
</tr>
Thanks
$("table input:radio").change(function () {
alert( $(this).closest("tr").children(".descriptionFound").text() );
});
Or, more elaborate:
// prepare once
$("table input:radio").each(function () {
var descr = $(this).closest("tr").children(".descriptionFound").text();
$(this).data("descr", descr);
});
// use
$("table input:radio").change(function () {
alert( $(this).data("descr") );
});
Inside the event callback function you can use this code to get the content of the description element.
$(this).next('.descriptionFound').text();