I am using .val() to set the values in HTML. My code is like this:
function first(){
var a=1;
$("#pg_textbox").val(a);
}
Now this code sets vales in my hidden HTML id 'pg_textbox':
<input type="hidden" id="paging_textbox">
On the second function call, it is like this:
function secound(){
var b=2;
$("#pg_textbox").val(b);
}
Now when I use:
$("#pg_textbox").val();
to get the value of '#pg_textbox' i am getting output is
2
It is replacing the values. I want my output like:
1,2
How can I get this output without replacing the value?
Thanks.
When you call .val(b), you do reset the entire value of the textbox. Calling .val() will only retreive what's in the textbox, it has no recollection of past values.
You'll need to update your setter:
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);
Try this code
var b=1;
var old_val=$("#pg_textbox").val();
$("#pg_textbox").val(old_val+" ,"+b);
You mean you're adding values to the input type, and don't want them to be replaced?
Well here's what you need to do then.
You need to make another hidden input type which will store the sum.
<input type="hidden" id="backup"/>
function first(){
var a=1;
$("#pg_textbox").val(a);
$("#backup").val(a);
}
function second(){ // Your second function
var b=1;
var sum = $("#backup").val()+b;
var old_val = $("#pg_textbox").val();
$("#pg_textbox").val(old_val+','+sum);
}
Also, you can continue this series with third, fourth, and so on...
This is what you're after.
var a = 1,
b = 2;
$("#pg_textbox").val(a + ', ' + b);
Although my code is technically correct, I can't imagine any practical application for it. Since you want to output some comma-separated values, it might be wiser to enter your values in an array, e.g.,
var yourValues = [1,2],
output = yourValues.toString();
$('#pg_textbox').val(output);
Check if there's a value already, if there is, concatenate the values...
var newVal = 2;
var prevVal = $("#pg_textbox").val();
if (prevVal == '')
{
$("#pg_textbox").val(newVal);
}
else
{
$("#pg_textbox").val(prevVal + ',' + newVal);
}
Update this:
var b=2;
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);
Related
For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.
When someone clicks the button it runs addKeyword and grabs the value of the input.
Tried to Console.Log the keyText variable and didn't work at all.
var keywords = [];
var keyText = "";
function addKeyword() {
var keywordName = document.getElementById("keywordAdd").value
keywords.push(keywordName);
keywords.forEach(showKeywords);
function showKeywords(item, index) {
var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
keyText.concat(newString);
document.getElementById("keywords").innerHTML = keyText;
}
}
No Errors shown in Console. Expected result is a list of but doesn't show.
The problem is that .concat doesn't mutate the string, it returns a new string.
You need to do something like this:
keyText = keyText.concat(newString);
By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:
const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;
Titus answer is correct, but you can simply use :
keyText += newString;
I have a situation, hope experts here will help me to sort it out. I need to get "id" values for first three tags and than on console.log print the values with comma separated.
I have managed to get the values from tag and print it on output. However, I am not able to comma separate them, and the issue is I am getting id of all the number of articles rather than only 3.
This is the jquery code that I come up with
jQuery(document).ready(function($) {
$("article").each(function() {
var info1 = $(this).attr("id");
var info2 = info1.replace( /[^\d]/g, '');
console.log(info2);
});
});
And this is the test
http://jsfiddle.net/0mvjbkhs/1/
Please note that I am not able to do any changes to html, all I can do is to get things done using jquery.
Please help to fix my code, So my output will looks like
[155569, 155570, 155571]
Thank you,
Use the jQuery .map() method which returns an array; if you need a single comma-delimited string, use the JavaScript .join() method. Don't forget :lt(3) which say you want the first three:
var arr1st3 = $('article:lt(3)').map(function() {
return this.id.replace(/[^\d]/g, '');
}).get();
console.log( arr1st3 );//OUTPUT: ["155569", "155570", "155571"]
//If you want [155569, 155570, 155571] as output
//use return +this.id.replace(/[^\d]/g, ''); instead
DEMO
jQuery(document).ready(function($) {
// search by the attribute
var ids = $('article')
// Take only the first three items
.slice(0, 3)
// Loop them to return an array
.each(function() {
// Get just the id and put that in the array
return this.attr('id');
});
// Format your output
console.log('[' + ids.join(', ') + ']');
});
http://jsfiddle.net/0mvjbkhs/4/
jQuery(document).ready(function($) {
var articles = [];
$("article").each(function() {
var info1 = $(this).attr("id").replace( /[^\d]/g, '');
articles.push(info1);
if (articles.length == 3) {
// break;
return false;
}
});
console.log('[' + articles.join(', ') + ']');
});
I am attempting to enter in 3 number input fields in my HTML, listed below:
HTML File-
<label for="num1">Enter number 1.</label><input type="text" size="20" id="num1">
<label for="num2">Enter number 2.</label><input type="text" size="20" id="num2">
<label for="num3">Enter number 3.</label><input type="text" size="20" id="num3">
<div id="greatestbutton" class="button">Click here to get the Greatest Number!</div>
<div>The greatest number is <span id="num1 || num2 || num3"></span></div>
Once these number have been entered, I want to ensure that they are indeed numbers and not letters and I wanted to take the greatest of those that have been entered:
JS File-
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber(num1, num2, num3) {
var a = parseFloat(num1);
var b = parseFloat(num2);
var c = parseFloat(num3);
var greatest = Math.max(a, b, c);
return greatest;
}
}
I can 'see' the 'button' accept the click, but I am unable to get it to return anything, let alone the greatest number.
Any help for this newbie would be greatly appreciated!!
Thanks!!!
Change the result element's id first:
<div>The greatest number is <span id="result"></span></div>
Then modify the button click function a little:
var button = document.getElementById("greatestbutton");
button.onclick = function() {
var num1 = document.getElementById('num1').value; // get value from inputs
var num2 = document.getElementById('num2').value;
var num3 = document.getElementById('num3').value;
var a = parseFloat(num1);
var b = parseFloat(num2);
var c = parseFloat(num3);
var greatest = Math.max(a, b, c);
document.getElementById('result').innerHTML = greatest; // set value for result
}
You aren't passing any values to the function greaterNumber, it doesn't just take values automatically. In this case you want to give it the values from the input fields, you can do that in a lot of ways, one of them being:
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber() {
var a = parseFloat(document.getElementById('num1').value); // get value
var b = parseFloat(document.getElementById('num2').value);
var c = parseFloat(document.getElementById('num3').value);
var greatest = Math.max(a, b, c);
return greatest;
}
return simply returns the value to whatever you call it from, in this fiddle i used alert instead just to prove that it works http://jsfiddle.net/NMys3/
A couple of points:
1) You seem to be assuming that the form's input values will be passed automatically as arguments to the event callback. They will not - all that's passed to the event callback is the event object itself. You need to grab those values manually, yourself.
2) You can't merely return the value from the event callback - you need to do something with it.
3) You don't say what should happen if one or more values are not numbers; presumably a message should appear or something, which is what I've assumed.
4) Not sure what you meant by that weird id attribute on the span; it seems like you've made a lot of assumptions about how code works here. Give it an ID of something like "max_num".
Try:
document.querySelector('#greatestbutton').addEventListener('click', function() {
var num_nums = 3, nums = [];
for (var i=0; i<num_nums; i++) {
var val = document.querySelector('#num'+(i+1)).value;
if (!parseFloat(val)) { alert('bad input!'); return false; }
nums.push(val);
}
document.querySelector('#max_num').innerHTML = Math.max.apply(null, nums);
}, false);
Note I have also...
1) Modernised the code slightly; it's better to register events using addEventListener (for reasons that are beyond the scope of this question) and I've used the ECMA5 jQuery-like method querySelector, which finds elements by CSS-style syntax
2) Made it dynamic for N numbers; your code is hard-coded to three, and requires more lines of code should this number be increased at any point
I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});
I'm trying to write a order form that shows the value of the selected items automatically. The backend is already complete, and on the front end each field, all radio / checkbox, look like this:
<input type="radio" name="shirt-size" value="shirt_size_m[18]" />
'18' being the price, everything else being irrelevant to the front end price calculation. I cannot change the naming convention, so I need to get the value between the brackets on all the <input>s on the page (or below the parent ID), add them together (on update), and append the value to another ID. Jquery is already in use on the site if that makes thongs easier.
I just need to be pointed in the right direction as my JS experience is limited to examples and minor customizations :)
Try using a simple regular expression with Javascript's replace, to replace all non-numeric characters with the empty string:
var str = "shirt_size_m[18]";
var theNumber = parseInt(str.replace(/[^0-9]/g, ''));
alert(theNumber);
Demo: http://jsfiddle.net/XvTaY/1/
You could try something like this:
function calculate_sum(form_id) {
var $form = $(form_id);
var sum = 0;
$checkbox_and_radios = $form.find('input[type=checkbox], input[type=radio]').each(function(){
sum += parseInt($(this).val().match(/^[^\[]+\[(\d+)\]$/)[1]);
});
return sum;
}
$(function(){
$("#id_of_the_form").find('input[type=checkbox], input[type=radio]').change(function(){
var sum = calculate_sum("#form_id");
// I don't know the type of your element containing
// the sum, so I put multiple solutions here:
// some input element
$('#another_id').val(sum);
// or another element
$('#another_id').html(sum);
// I'm assuming you don't really mean append
// If you're sure you want to append: (but then the old value won't be deleted)
$('#another_id').append(sum);
});
});
u can use:
var v;
v = $('#input-identifier').val();
v = v.split("[");
v = v[1];
v = v.split("]");
v = v[0];
// now v has the number