I have a set of inputs which can be duplicated, but I then need to increment the array value of them. How do I do this?
<input type="text" name="person[0][name]">
<input type="text" name="person[0][age]">
This can then be duplicated, but I need to change the new inputs to be like:
<input type="text" name="person[1][name]">
<input type="text" name="person[1][age]">
I have got so far:
cloned.find('input, select').each(function(){
var $this = $(this);
$this.attr('name',
$this.attr('name').match(/\[\d+]/g, '[' + what_goes_here + ']')
);
});
Where cloned is my last group of inputs.
What do I do with the value of what_goes_here?
You can use .match() with RegExp \d+, + operator, .replace()
cloned.find('input, select').each(function() {
var $this = $(this);
var n = $this.attr('name').match(/\d+/)[0];
$this.attr('name', $this.attr('name').replace(n, +n + 1));
});
Related
MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.
I have such code in my view:
<div class="box">
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
</div>
In my js I'd like to change [1] into [2] or [3] and so on after [quantity], depending on how many additional forms I create. How can I do that?
This is what I have in my JS:
var i = 1
$('.add_another_price_btn').click( function (e) {
e.preventDefault();
$(this).prev().clone().insertBefore($(this));
$(this).prev().find('.remove_another_price_btn').show();
$(this).prev().find('.product_quantity').removeAttr('readonly');
$(this).prev().find('.product_quantity').attr('value', '');
//This is what I tried, but it doesn't work properly.
$(this).prev().find('.product_quantity')
.attr('name', function() { return $(this).attr('name') + '['+ (i++) + ']' });
$('.remove_another_price_btn').click( function (ee) {
ee.preventDefault();
$(this).parent().parent().remove();
});
You can do a simple string operation with substr and lastIndexOf to replace the last part of the name.
// get input and name of input
var input = $("input");
var name = input.attr("name");
// change just the last part
name = name.substr(0, name.lastIndexOf("[")) + "[2]";
// set name back to input
input.attr("name", name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
Save the clone
Break the name using substring or split and parseInt
Like this
var $clone = $(this).prev().clone(),
$prodQ = $clone.find('.product_quantity'),
name = $prodQ.attr("name"),
parts = name.split("quantity]["),
newName = parts[0]+"quantity][",
num = parseInt(parts[1],10); // or a counter
num++;
newName += num+"]";
$prodQ.removeAttr('readonly').attr('value', '').attr('name',newName);
$clone.insertBefore($(this));
$clone.find('.remove_another_price_btn').show();
I have this HTML where the Id contains special charaters:
<input type="text" id="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" value="">
<input type="hidden" id="Type_e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" name="Type_e09b989c-7201-4b7e-8fd4-a2309db6d356|b5d9746a-7f7c-432d-a4ef-a5e0011d989d|IssueDate" value="date">
<br>
<input type="text" id="1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" name="1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" value="" class="">
<input type="hidden" id="Type_1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" name="Type_1c36b33a-85d8-4811-93f6-a5e000ad985c|b795c0b4-1c8b-4d9e-95c5-a5e0011d8505|FromDate(mm/dd/yyyy)" value="DateTime">
And i am using this JQuery to update them:
$("input[id^='Type_']").each(function () {
if ($(this).val() == "date" || $(this).val() == "DateTime") {
console.log($(this).attr('id'));
var id = $(this).attr('id').replace("Type_", "").replace(/\|/g, "\\|").replace(/\//g, "\\\\\/").replace(/\)/g, "\\\\\)").replace(/\(/g, "\\\\\(");
console.log(id);
console.log(">>" + $("#" + id));
$("#" + id).val(id);
}
});
But the second Id which contains "|" and "(" is not selected.
I am testing here: http://jsfiddle.net/MWadX/446/
Can somebody help me?
Thanks.
The problem is how you are escaping the special characters,
var id = this.id.replace(/[|\(\)#\\\/]/g, '\\$&');
Demo: Fiddle
$("input[id^='Type_']").each(function() {
if ($(this).val() == "date" || $(this).val() == "DateTime") {
var tempID = $(this).attr('id');
var temp_ID1 = this.id.replace(/[|\(\)#\\\/]/g, '\\$&');
console.log(temp_ID1);
console.log("#" + temp_ID1);
}
});
Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});
I have that in my html
<input type="checkbox" id="1234">
<input type="checkbox" id="2345">
<input type="checkbox" id="3456">
<input type="checkbox" id="4567">
<input type="checkbox" id="5678">
And an list of id 1234 2345 3456 or #1234 #2345 #3456
I want to get all the element of the list whose id is in the list of id
I try $(":checkbox").attr('id', items_id); and var items_cb = $(":checkbox[id='items_id']"); where items_id is the list of item, but it doesn't work.
Just try to put all id's in selector separated by comma:
$('#1234, #2345, #3456')...
Code: http://jsfiddle.net/3df6W/
P.S. ID's shouldn't start with digits.
Try this
$('#1234, #2345, #3456')
You can use the jQuery each method that will loop through all the selected elements.
HTML
<input name="myradio" type="checkbox" id="colour1">
<input name="myradio "type="checkbox" id="colour2">
<input name="myradio" type="checkbox" id="colour3">
JavaScript
$('input:radio[name=myradio]').each(function (index) {
alert(index + ': ' + $(this).val()); //is it checked?
alert(index + ': ' + $(this).attr('id')); //ID string
//You can compare if is this ID in items_id in this loop
});
var arr = ['1234', '2345', '3456'];
var elem = [];
$('body > input').filter(function() {
if ($.inArray(this.id, arr) != -1) {
elem.push({
id: this.id,
type: $(this).prop('type'),
name: this.nodeName
});
}
});
console.log(elem);
console.log(elem.length);
you can just build a selector string like :
var selectorString = '';
for id in idList:
selectorString = '#' + idList[id] + ',';
then you can use the selectorString as :
$(selectorString)
to select them.
var result = [];
for(var i=0; i < items_id.length; i++){
var id = items_id[i];
result.push($(id))
}
// result is what you want
$("#1234, #2345, #3456")
...should work.
http://api.jquery.com/multiple-selector/