jQuery - Dynamically amend Input name with multiple dimensional array - javascript

I have an input field which looks something like this...
<input type='hidden' name='myInput[1][sausages][0][]' value='123' />
I need to change the value in the third set of square brackets when a user clicks on a button...
so something like
$("a.mylink").click( function() {
$(this).siblings('input[name*=myInput]')..... CHANGE THE 0 to 1 in the third set of square brackets...
});
Any ideas how I can do this?

Try This:
$('input').attr('name',$('input').attr('name').replace(/\[\d+](?!.*\[\d)/, '[1]'))
Working Demo

You can use regex to replace the value like so:
var name = $('input [name*=myInput]').attr('name');
name.replace(/]$/, 'new value]');
$('input [name*=myInput]').attr('name', name);
The new value can be any number
This regex replaces the last bracket with a new value: newvalue ]
Or if you want to change the 2nd to last bracket you can use this regex:
name.replace(/]\[\]$/, 'new value][]');

Try this
var name = $('input[name*=myInput]').attr('name');
var indexOfThirdBracket = name.indexOf('[', name.indexOf('sausages')) + 1;
name = name.substring(0, indexOfThirdBracket) + '1' + name.substring(indexOfThirdBracket + 1);
$('input[name*=myInput]').attr('name', name);
http://jsfiddle.net/3A592/
UPDATE
Solution without hard code value 'sausages'
var name = $('input[name*=myInput]').attr('name');
var parts = name.split('[');
parts[3] = parts[3].replace('0', '1');
name = parts.join('[');
$('input[name*=myInput]').attr('name', name);
http://jsfiddle.net/56rtG/

use this code:
var counter = 1;
$('a.mylink').click(function(){
$(':text').attr('value', 'myInput[1][sausages][' + counter++ + '][]');
});

Related

Put value straight into input textbox form?

I'm grabbing a the last transaction value from https://api.bitcoinaverage.com/ticker/global/CAD/ and want to update it into an input textbox, but no matter what I try it won't show up.
here's a fiddle
https://jsfiddle.net/h9w5tj8m/2/
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').innerHTML = price;
}
};
xbtc.send();
updated fiddle
use
document.getElementById('cad').value
instead of
document.getElementById('cad').innerHTML
Simply understand with user interacted element input,select,textarea all are call with value for get the data from the elements.
All Other element's are call with innerHTML for get the data from the element
also refer different between .value and .innerHTML
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').value = price;
}
};
xbtc.send();
There is no input type of "textbox". You need to change it to "text" or use a <textarea></textarea>. You can set the value of text input with .value and a textarea with .innerHTML or .value.
This fiddle works fine: https://jsfiddle.net/h9w5tj8m/4/
using value attribute will place the value u retrieved into a particular textbox having a specific id .For Example :
<input type ="textbox " id="a">
</input>
<script>
document.getElmentById("a").value=x;
</script>
//x is the variable where the retrieved data is stored.
try this
document.getElementById('cad').value = price;

Dynamic id for HTML element which is getting created newly

I am replacing a span inside a table > td with option box.
I want to assign some unique id with dynamic value while creating the option box. How to achieve this?
Unique id is already generated , I want to set this unique id in Html while creation.
<td id="tdTest">
<span id="spanId" class="connectedSlot" style="color:rgb(27,99,173)">Enabled</span>
</td>
$("#"+spanId).replaceWith(function () {
return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});
For example , I will get some value from and assign to a variable and later assign this variable to id.
var myId = "OptionId"+test;
select class='form-control' id=myId style='width:200px;'>
Thanks
Use a variable within a string like this:
var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";
One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.
getUniqueId() is a function that will always return a unique id.
function getUniqueId() {
//get all the ids in this document
var ids = new Array();
$('[id]').each(function() { //Get elements that have an id=
ids.push($(this).attr("id")); //add id to array
});
//give some random value to uniqueId
//if this value is in ids array, then assign a different id and recheck the condition
var uniqueId;
while(true) {
uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
if($.inArray(uniqueId , ids) == -1) {
break;
}
}
return uniqueId;
}
Possible Solution:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Look into these Questions for others: link link
It's been several years since this was posted, and the accepted solution didn't work for me. Here is the syntax that did:
[id]="unqiueID"

Adding more than one value to text box

I'm trying to allow users to add a list of 'favourites' to a text box but when adding more than one value it replaces the value already there. Can anybody help? Thanks this is my code:
var name
function getFavourite() {
name = "Student 1, ";
$('#output').val(name)
saveFavourites();
}
function getFavourite2() {
name = "Student 2, ";
$('#output').val(name)
saveFavourites();
}
function saveFavourites() {
var fav = $("#output").val();
if (fav !== "") {
localStorage[name] = $("#output").val();
$("#output").val(name);
}
}
function loadFavourites() {
var fav = $("#name").val();
if (name !== "") {
$("#output").val(localStorage[name]);
$("#name").val("");
}
}
using val will replace the existing value as you already noticed so i would do something like this if you want to add to that value.
$("#output").val($("#output").val() + ', ' + name);
At least if i understand you correctly. This would get the excising value and then add the new value to it (in this case with a comma but is not necessary)
Of course if you need the same element twice or more is better to assign it to a var instead of calling the selector twice.
I think you are looking into multiple select dropdown, something like this:
http://codepen.io/martynasb/pen/kawxq
You don't an text input, you want a select where you can select multiple values. In html, it's <select multiple>.
The plugin I know that provides the best experience for this is is Select2: http://ivaynberg.github.io/select2/#basics
And you don't have to load all the options right away, they can be fetched via ajax easily.

Need help with regular expression and javascript

I've following problem: I use a clone script to clone input fields which are used for cms options. Depending on the field name the option arrays are created in the db.
I have following field at the moment:
options[categories][1][3]
and want to increase the first number by using a counter variable like:
options[categories][2][3]
options[categories][3][3]
...
However I'm not familiar with regular expressions so I hoped someone could provide a str.replace code which helps me to replace the first number with my counter variable.
Thanks in advance!
.......
Code:
.......
At the moment it looks like:
if ( $(clone).attr('name') ){
newid = $(clone).attr('name');
var position = newid.lastIndexOf("[");
newid = newid.substring(0, position)+ '[' + (counter +1) + ']';
$(clone).attr('name', newid);
};
Html field:
<input type="checkbox" value="1" name="options[categories][1][3]">
3 is the category id, 1 is the option I need the category for. The clone script would produce:
<input type="checkbox" value="1" name="options[categories][1][4]">
at the moment - but I need:
<input type="checkbox" value="1" name="options[categories][2][3]">
I think it's a regex problem because the easiest solution would be to search for [categories][anyvalue] and replace it with [categories][counter]
You could use a regular expression to replace the first number in brackets. Like this:
if ( $(clone).attr('name') ) {
var newid = $(clone).attr('name');
newid = newid.replace(/\[[0-9]*\]/, '[' + (counter + 1) + ']');
$(clone).attr('name', newid);
};

jquery value substitution

Is this a ligitimate way of determining the selected value of an section/option box with and id of "shirt_size_1221"?
var user_id = '1221';
x = "#shirt_size_" + user_id ;
alert($(x + " option:selected"));
Your alert statement will always show [object] unless you change it to
alert($(x+' option:selected').val());
And don't worry, this is a good way of getting selected option.
You can get the value of a selected option in a dropdown box by using
var selectList = document.getElementById("shirt_size_1221");
var val = selectList.options[selectList.selectedIndex].text;
No JQuery needed.
The "proper" way is simply:
var user_id = '1221';
x = "#shirt_size_" + user_id ;
alert($(x).val());

Categories