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
Related
Write a function named "additionCalculator" that that doesn't take any parameters and doesn't return a value. This function will control the logic for a web-based calculator that adds two numbers. There will be two text boxes on the web page with ids of "input_one" and "input_two" and an empty div with an id of "sum". Read the values of the two text boxes and write the addition of these two values inside the div.
function additionCalculator(){
var one = parseInt(document.getElementById('input_one'));
var two = parseInt(document.getElementById('input_two'));
var sum = one + two;
document.getElementById('sum').value = sum;
}
I can't seem to add the two numbers together. What am I doing wrong?
document.getElementById returns an HTML element - you want the value of the element (I assume these are inputs) - so you need to get the actual property:
var one = parseInt(document.getElementById('input_one').value);
var two = parseInt(document.getElementById('input_two').value);
When setting the value back to the div - use the innerHTML property:
document.getElementById('sum').innerHTML = sum;
Try this, I think what you're missing is a button that calls the action for the calculation to happen. Also remember to change your statements to get the value of the inputs and to target the innerHTML of the empty div
document.getElementById('sumBtn').onclick = function additionCalculator(){
var one = parseInt(document.getElementById('input_one').value);
var two = parseInt(document.getElementById('input_two').value);
var sum = one + two;
document.getElementById('sum').innerHTML = sum;
}
<input type="text" id="input_one">
<input type="text" id="input_two">
<button id="sumBtn">Add</button>
<div id="sum"></div>
So, I have this function that, after an update, deletes elements from a table. The function, lets call it foo(), takes in one parameter.
foo(obj);
This object obj, has a subfield within called messages of type Array. So, it would appear something like this:
obj.messages = [...];
Additionally, inside of obj.messages, each element contains an object that has another subfield called id. So, this looks something like:
obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];
Now, in addition to the parameter, I have a live table that is also being referenced by the function foo. It uses a dataTable element that I called oTable. I then grab the rows of oTable and copy them into an Array called theCurrentTable.
var theCurrentTable = oTable.$('tr').slice(0);
Now, where it gets tricky, is when I look into the Array theCurrentTable, I returned values appear like this.
theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];
The loop below shows how I tried to show the problem. While it works (seemingly), the function itself can have over 1000 messages, and this is an extremely costly function. All it is doing is checking to see if the current displayed table has the elements given in the parameter, and if not a particular element, delete it. How can I better write this function?
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
var deletionPending = true;
for(var x = 0; x < theReceivedMessages.length; x++){
var messageID = theReceivedMessages[x].id;
if(diplayID == messageID){
console.log(displayID+' is safe...');
deletionPending = false;
}
}
if(deletionPending){
oTable.fnDeleteRow(idx);
}
}
I think I understand your problem. Your <tr> elements have an id that should match an item id within your messages.
First you should extract the message id values you need from the obj parameter
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });
This will give you all the rows ids you need to keep and then join the array together to use jQuery to select the rows you don't want and remove them.
$('tr').not(ids.join(',')).remove();
Note: The Array.prototype.map() function is only supported from IE9 so you may need to use jQuery.map().
You could create a Set of the message ID values you have, so you can later detect if a given ID is in this Set in constant time.
Here is how that would look:
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
// Now you can skip the inner loop and just test whether the Set has the ID:
if(!ids.has(displayId)) {
oTable.fnDeleteRow(idx);
}
});
So now the time complexity is not any more O(n.m) -- where n is number of messages, and m the number of table rows -- but O(n+m), which for large values of n and m can make quite a difference.
Notes:
If theCurrentTable is not a true Array, then you might need to use a for loop like you did, or else use Array.from(theCurrentTable, function ...)
Secondly, the implementation of oTable.fnDeleteRow might be that you need to delete the last rows first, so that idx still points to the original row number. In that case you should reverse the loop, starting from the end.
I am trying to use a variable of a textareas value but I don't want the entire value only the new word that is being written.
What I've tried doing is something like this-
function getValue(ele,array){
var a = ele.val();
array.push(a);
}
function newWord(ele,array){
var b =ele.val();
array.toString.match(b);
}
$(function() {
$('#textarea').keyup(function() {
var array = [];
getValue($(this),array);
console.log(array);
var c = newWord($(this),array);
console.log(c);
});
});
What I was hoping for is that it would get the newly typed word. All I want to do is get that new word that is being typed up until a space is entered. And I was working with a few plugins that would getSelection for all modern browsers and well that just didn't work for me as well.
Does anyone have a suggestion on the best way to do this? I don't mind on keep trying myself just need a little hand to lead me on the right path to get my full code working the way I need it to. Full Code is here http://jsbin.com/obihig/1/edit it is a Auto Suggestion, for textarea, and it needs to be for every word being written.
$(function() {
$('#textarea').keyup(function() {
var array = [];
var newWord;
array = this.val().split(' ');
console.log(array);
newWord = array[array.length - 1]
console.log(newWord);
});
});
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');
I am using jQuery Serialize to serialize my form elements and would like to deserialize them back. Unfortunately can't find any working jQuery deserializer, any suggestions?
I wrote a version of jQuery.deserialize that supports serialized data generated from the serialize, serializeArray and serializeObject functions. It also supports all form element types, including checkboxes and radio buttons.
Try this:
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}
I was very interested in trying JQuery.deserialize, but it didn't seem to handle checkboxes at all, so it didn't serve my purposes. So I wrote my own. It turned out to be easier than I thought, because the jQuery val() function does most of the work:
jQuery.fn.deserialize = function (data) {
var f = this,
map = {},
find = function (selector) { return f.is("form") ? f.find(selector) : f.filter(selector); };
//Get map of values
jQuery.each(data.split("&"), function () {
var nv = this.split("="),
n = decodeURIComponent(nv[0]),
v = nv.length > 1 ? decodeURIComponent(nv[1]) : null;
if (!(n in map)) {
map[n] = [];
}
map[n].push(v);
})
//Set values for all form elements in the data
jQuery.each(map, function (n, v) {
find("[name='" + n + "']").val(v);
})
//Clear all form elements not in form data
find("input:text,select,textarea").each(function () {
if (!(jQuery(this).attr("name") in map)) {
jQuery(this).val("");
}
})
find("input:checkbox:checked,input:radio:checked").each(function () {
if (!(jQuery(this).attr("name") in map)) {
this.checked = false;
}
})
return this;
};
You should be able to use this like this:
$("#myform").deserialize(data);
Where data is a parameter list such as what $("#myform").serialize() would produce.
It affects all fields in the form, and it will clear the values of fields that are not contained in the data. But you can also pass any selector to affect only specific fields, as you can with the serialize function. E.g.:
$("select").deserialize(data);
Half of jQuery Serialize is param(), so half of something that deserializes a query string is going to be a deparam. Unfortunately I haven't been able to find a good standalone deparam. For now I recommend getting the jQuery BBQ library and using that. If you don't need the other stuff you can remove them. I read somewhere that Ben Alman (cowboy) planned to extract deparam into its own module.
For the rest of deserializing, you'll just need to loop through the object that deparam returns and for each key and value pair in the object, select the form element based on the key, and set the form elements value to the value.
Bit late on this one, but somebody might find this useful.
function fetchInput(identifier) {
var form_data = identifier.serialize().split('&');
var input = {};
$.each(form_data, function(key, value) {
var data = value.split('=');
input[data[0]] = decodeURIComponent(data[1]);
});
return input;
}
I'm not now answering your question but my guess is that you want to serialize it and send back to server and then use the serialized data which is why you have to deserialize it?
If that's the case you should consider using .serializeArray(). You can send it as POST data in ajax, and then access later as well because you will have object.
May be a bit late, but perhaps you are looking for something like JQuery.deserialize. Problems: no support for checkboxes or radio buttons.
Using Jack Allan's deparam function with jQuery, you can change this line:
map[key] = value;
to
$('input[name=' + key + ']').val(value);
Which will load the data back into your form fields.
this code returns an array when same key is spotted multiple times in the serialized string
chaine="single=Single1&multiple=Multiple&multiple=Multiple1&multiple=Multiple2&multiple=Multiple3&check=check2&radio=radio1"
function deserialize(txt){
myjson={}
tabparams=chaine.split('&')
var i=-1;
while (tabparams[++i]){
tabitems=tabparams[i].split('=')
if( myjson[decodeURIComponent(tabitems[0])] !== undefined ){
if( myjson[decodeURIComponent(tabitems[0])] instanceof Array ){
myjson[decodeURIComponent(tabitems[0])].push(decodeURIComponent(tabitems[1]))
}
else{
myjson[decodeURIComponent(tabitems[0])]= [myjson[decodeURIComponent(tabitems[0])],decodeURIComponent(tabitems[1])]
}
}
else{
myjson[decodeURIComponent(tabitems[0])]=decodeURIComponent(tabitems[1]);
}
}
return myjson;
}
Needed all in a single string, which can be stored in maybe COOKIE, and later read and fill the same form with input values.
Input elements seperator: ~ (use any seperator)
Input attributes seperator: | (use any seperator)
input type | input name | input value ~ input2 type | input2 name | input2 value
var formData = '';
$('#form_id').find('input, textarea, select').each(function(i, field) {
formData += field.type+'|'+field.name+'|'+field.value+'~';
});
Example:
hidden|vote_id|10~radio|option_id|~radio|option_id|427~radio|option_id|428~
If what you want is to remove the standard URL-encoded notation, you can use JavaScript's decodeURIComponent(), which will give you a regular string, just like this:
var decodedString = decodeURIComponent("Http%3A%2F%2FHello%3AWorld");
alert(decodedString);
In this case, decodedString will look like Http://Hello:World, here's a working fiddle.
Got all of this searching for this same issue, and found the answer here: How can I decode a URL with jQuery?
I know this is an old question, but doing some searches for jQuery deserialize got me here, so I might as well try to give a different approach on the issue for people with the same problem.