name attribute self references id - javascript

In short, is there some self reference code to set the name attribute equal to the id?
for example,
<input name="this.id" id="input1">
In long, using .serialize() requires use of the name attribute. Hypothetically, there is a form that contains many inputs without name attributes. I'm aware of,
how I could (read, "should") add name attributes that match the id's to each input,
creating a separate function to serialize the form using id attribute,
similar solution like in this question,
the steps taken to submit a form.
However, in some research on SO, I was led to believe that if a person were to use,
<input name="id[]" id="input1">
when serialized, the name would have the id appended to it. In my tests this method produces id%5B%5D (url encoded string of id[]). Using anything available, is there a short hand way to set the name attribute so that it references the id attribute on each input?

There is nothing in HTML that will do the reference so you will need to set it manually. The best solution, set it when you build the form. Or set it when you reference the elements
console.log($("input").attr("name", function (){ return this.name || this.id }).serialize())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo1" value="1" />
<input id="foo2" value="2" />
<input id="foo3" value="3" />
<input id="foo4" value="4" />
or just write your own method
$.fn.serializeId = function() {
return $(this).map(function(){
return this.id + "=" + encodeURIComponent($(this).val())
}).get().join("&");
}
console.log($("input").serializeId())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo1" value="1" />
<input id="foo2" value="2" />
<input id="foo3" value="3" />
<input id="foo4" value="4" />

Related

Javascript - copy field values without knowing all the fields

I have input fields that are associated together, and need to copy value from "parent" field to "child" field when something is entered into "parent" field. In short, it should work like this jsfiddle.
<form id="form1" method="..." action="...">
<p><label>Enter something: <input name="parent1"></label><br>
<label>and see what happens: <input name="child1"></label></p>
</form>
<script>
var form = document.getElementById('form1');
form.elements.parent1.onblur = function () {
var form = this.form;
form.elements.child1.value = form.elements.parent1.value;
};
</script>
Simple. Now here's the problem: I don't know how many fields the form will have (these are created dynamically). All I know is there will always be the same number of parent/child fields and their names will be the same. So form may look like:
<input name="parent[59]"> <input name="child[59]">
<input name="parent[87]"> <input name="child[87]">
...and so on. Yes, the field names are the same, except the number (because these need to be submitted as arrays) will be different.
How do I rewrite JS code, so when user enters something into parent[59], its value gets copied to child[59], when user enters something into parent[87], its value gets copied to child[87], etc?
I couldn't even get it working with single field when names of input fields contain square brackets jsfiddle
(yes, I tried escaping brackets with \ but no luck)
You can target all elements based on the attribute, and then fetch the number from the name
document.querySelectorAll('[name^=parent]').forEach(function(elem) {
elem.addEventListener('input', function() {
var n = this.name.split('[').pop();
document.querySelector('[name="child[' + n + '"]').value = this.value;
});
});
<input name="parent[59]"> <input name="child[59]">
<br /><br />
<input name="parent[87]"> <input name="child[87]">
<br /><br />
<input name="parent[187]"> <input name="child[187]">
<br /><br />
<input name="parent[3]"> <input name="child[3]">
A very simple solution is to use an Event Delegate to listen to all input events on the DOM, then if the target (i.e. event.target) element has a name attribute which contains the string literal "parent" (check using String.indexOf()), replace that with "child" (using String.replace()) and update the element with that name attribute.
document.addEventListener('input', function(inputEvent) {
if (inputEvent.target.name.indexOf('parent') > -1) {
var childName = inputEvent.target.name.replace('parent', 'child');
document.forms[0].elements[childName].value = inputEvent.target.value;
}
});
<form id="form1">
<input name="parent[59]"> <input name="child[59]">
<br /><br />
<input name="parent[87]"> <input name="child[87]">
<br /><br />
<input name="parent[187]"> <input name="child[187]">
<br /><br />
<input name="parent[3]"> <input name="child[3]">
</form>
Compare that with the non-delegate approach (Adding an event listener to all parent inputs, which requires iterating over DOM elements with class name containing parent) in this jsperf testcase. When I ran it, the non-delegate case was 33% slower.
Comparing the two approaches through the lens of algorithmic complexity, the delegate approach is a constant time algorithm, so it is Θ( 1 )1, whereas the non-delegate approach is linear, or Θ( n )1. In other words, the worst-case for the event delegate approach is that it runs once per page load, whereas the other approach will have the lambda function run as many times as there are elements with the string literal "parent" in the name attribute.
1http://discrete.gr/complexity/

Identical ID's in the same HTML page

I have a page that has two different inputs that contain same ID but each one in different form. and I'm actually setting values to inputs from javascript using get element by ID. I know this is not valid. but the thing is if i change one of the input id's I'm gonna need to re write a bunch of code in 'shopping cart ' cuz these input's pass value to cart. I'm actually not planning to touch that for now. So, is there any trick that can target one input instead of the other even if they have the same id's??
ex:
<input type="hidden" name="cart_1_ID_Add2" id="cart_1_ID_Add2" value=""/>
<input type="hidden" name=cart_1_ID_Add2" id="cart_1_ID_Add2" value=""/>
thanks in advance!!
Although it is a wrong practice, and you should use different id's, you could add a different class attribute to each one.
<input class="input1" type="hidden" name="cart_1_ID_Add2" id="cart_1_ID_Add2" value=""/>
<input class="input2" type="hidden" name=cart_1_ID_Add2" id="cart_1_ID_Add2" value=""/>
var x = document.getElementsByClassName("input1")[0];
Again: I strongly recommend you to find time to change the logic of your program to use unique id's.
If they are in different forms you can target them by selecting IDs where they are inside a certain class. You can also change the name attribute and select that instead.
HTML
<div class="form1">
<input type="hidden" name="rename1" id="cart_1_ID_Add2" value="">
</div>
<div class="form2">
<input type="hidden" name="rename2" id="cart_1_ID_Add2" value="">
</div>
JS
$(".form1 #cart_1_id_add2")
//Or
$("input[name*='rename1']")
However you shouldn't really have the same id twice on one page otherwise it makes it hard to maintain and debug. If it's not a huge job to change your approach I'd recommend you do that.
Add another attribute to one or both tags.
For example, you can make them
<input type="hidden"name="cart_1_ID_Add2" id="cart_1_ID_Add2" data-id="add100" class="myInput" value=""/>
<input type="hidden" name=cart_1_ID_Add2" id="cart_1_ID_Add2" data-id="add101" class="myInput" value=""/>
Then get their values with jQuery
var myInput = $('[data-id=add100]').val();
console.log(myInput);
OR use plain javascript by adding a class and getting the value
var myVal = document.getElementsByClassName("myInput")[0];
console.log(myVal.value);
Hope this helps
Yes.
That code shouldn't have duplicate id properties in Dom btw.
You can use a custom HTML element property:
<input type="hidden" name="cart_1_ID_Add2" id="cart_1_ID_Add2" value="" my-property="some_identifier"/>
<input type="hidden" name=cart_1_ID_Add2" id="cart_1_ID_Add2" value="" my-property="some_identifier2"/>

how to get text associated in a html input tag of type checkbox

I have my element like below
<input type="checkbox" id="Countries" value="Ind">India</input>
How to get output as "India"?
Below returns only Ind
document.getElementById("Countries").value;
There is a way to get the value when you don't care about semantically correctness.
alert(document.getElementById('Countries').nextSibling.nodeValue);
<input type="checkbox" id="Countries" value="Ind">India</input>
For completeness:
You shoult do an input type like this as mentioned in the Form W3
<label for="Countrie">India</label>
<input type="checkbox" id="Countrie" />
or
<input type="checkbox" id="Countrie" />
<label for="Countrie">India</label>
or
<label>
<input type="checkbox" name="Countrie" />
India
</label>
also mentioned in THIS POST
and then use javaScript to get a coresponding label value.
I don't think that you can because that isn't valid HTML code.
An input tag is empty, meaning that it can only contain attributes. Therefore, there is no </input> to close it.
There are ways to store data in it though.
As of HTML 5, there is a data- attribute that you can put on any element. You could do something like this:
<input type="checkbox" id="Countries" value="Ind" data-something="India" />
// Inside JS
document.querySelector("#Countries").dataset.something
Another alternative would be to wrap a p or a span around the text after it.
<input type="checkbox" id="Countries" value="Ind" />
<p id="CountriesText">You can get this value easily enough</p>
This is not possible because your html is wrong.
input is a self closing tag, so it should be like this.
<input type="checkbox" id="Countries" value="Ind" />
So there is no other value you could extract with javascript then the value.
Or you should use a data-attribute with India as a value.
HTML
<input type="checkbox" data-country="India" id="Countries" value="Ind" />
JS
var checkbox = document.querySelector('#Countries'); // or document.getElementById("Countries");
alert(checkbox.dataset.country);
See this fiddle http://jsfiddle.net/zwx43m59/

jQuery get object by name when name contains a "["-character

Consider this HTML:
<input type="text" name="inputa[42]" value="2012-05-02" />
<input type="text" name="inputb[42]" value="74,178" />
<input type="text" name="inputa[85]" value="2013-02-14" />
<input type="text" name="inputb[85]" value="21,35" />
How to use a jQuery selector to get the value of the input with name inputa[85]?
It would have been very easy if the name wouldn't have contained [85], but now I can't get $("input[name=inputa[85]]") to work which is understandable, but how to solve it (without changing the name attribute)?
In quotes:
$("input[name='inputa[85]']")
or
$('input[name="inputa[85]"]')
You can use $('input[name*="inputa"]') if you don't know the value in brackets or abuduba's answer above.

How to set link to check checkbox with variable name,id,value

I have a long list of checkboxes each with a link next to it. Something like:
<form name="checkboxlist" action="..." >
<input type="checkbox" id="1" name="pageCB" value="1"/>
<a id="1" href="#" onclick="sub(id)>click here</a>
<input type="checkbox" id="2" name="pageCB" value="2"/>
<a id="2" href="#" onclick="sub(id)>click here</a>
...
...
<input type="submit" />
</form>
I am currently trying to use:
<script>
function sub(id){
$("input:checkbox[value=id]").attr("checked", true);
document.checkboxlist.submit();
}
</script>
But this obviously does not read the variable id and I would really like to avoid making if statements for each id as there are several hundred of them. Is there some way to do this?
You shouldn't use a link you should use a <label> tag.
That's what it's made for.
<input type="checkbox" name="mybox" id="mybox">
<label for="mybox">Click this box</label>
This works for all form fields and is way better than having to build JS to do something that already exists.
EDIT: I see you're also using duplicate IDs. This is invalid, and things will not work properly when selecting by ID.
Numeric IDs are invalid in HTML4.
Anyway, change this:
$("input:checkbox[value=id]")
to this:
$("input:checkbox[value='" + id + "']")
This concatenates the value of id into the selector string, and I also added quotation marks around the attribute selector value since they're required by the docs.
And change your inline handlers to this:
<a id="2" href="#" onclick="sub(this.id)>click here</a>
...because this is a reference to the element clicked, so this.id is a reference to its ID attribute.
If I understand correctly, you want to support selecting checkboxes by clicking on an associated element, and to submit the form on click. I would suggest a) Use a <label> element in place of <a> as they can be associated with inputs by id and b) don't use numeric, duplicate id attributes.
<form name="checkboxlist" action="#">
<input type="checkbox" id="a" name="pageCB" value="1"/>
<label for="a">Click here</label>
<input type="checkbox" id="b" name="pageCB" value="2"/>
<label for="b">Click here</label>
</form>
<script>
$(document).ready(function() {
$('input:checkbox').change(function(){
$(this).parent('form').submit();
});
});
</script>

Categories