Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I better make a list in order to explain the steps that I would like to do:
Get the name of the last element of the html-input (has been generated via PHP)
The basic setting looks like this:
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
Pass it over to a JS function
Append some additional fields (use part of the name as an id for new fields
The JS-script works fine and I am able to add fields. Also the content of the fields is being processed by the PHP script and written in a db.
Short: how do I get the last value, no matter how many fields there are?
edit: I had forgotten that there is a submit button that would appear as the last element as well ... sorry for that
There are a number of approaches, but given all other answers rely on the jQuery library (which adds an unnecessary overhead), I'll focus on showing some plain JavaScript approaches (works on recents browsers above IE8+).
var allTextInputs = document.querySelectorAll('input[type="text"]'),
lastInput = allTextInputs[allTextInputs.length - 1],
lastInputName = lastInput.name;
var allInputsTxt = document.querySelectorAll('input[type="text"]');
var lastInput = allInputsTxt[allInputsTxt.length - 1];
var lastInputName = lastInput.name;
var lastInputValue = lastInput.value;
alert('last input name : ' + lastInputName + '; last input value : ' + lastInputValue);
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
If what you want is the value and not the name attribute, do this after using the same approach as above to get the name of the last <input type="text"/>:
var lastInputValue = lastInput.value;
These approaches will give the value of the last <input /> of the type="text" in the document at the point at which the code is run; to find the value of a last <input /> that's dynamically added to the document, you'll need to re-run a working approach following that element's insertion.
jQuery...
var lastInputName = $('input[type="text"]:last').attr('name');
The following jQuery code should do the trick.
var lastValue = $("input[type=text]:last").val();
Also with jQuery:
var $inputs = $("input[type=text]");
var lastValue = $inputs[$inputs.length - 1].value;
Use CSS3 selectors in combination with sizzle (jquery) to target last element
var name = $('input[name^=E_]:last')[0].name
the last value in PHP or JavaScript?
in PHP the fields are normally passed as an array, so you can get the last value using
end($array)
Even better if you name your filed like this
<input type='text'name='E[8]' value= '123' />
<input type='text'name='E[9]' value= '456' />
<input type='text'name='E[10]' value= '789' />
in JS you need to get the fields into an array and get the last.... you need something like this
var myFields = document.forms["myform"].getElementsByTagName('input'),
var lastValue = myFields[(myFields.length-1)].value;
By wrapping your code a parent element, let's says with an attribute id="inputs", here is a vanilla DOM (no jQuery) solution :
// start by finding the last-most element
var lastInput = document.getElementById('inputs').lastElementChild;
// search backward to the last 'text' element
while (lastInput && lastInput.type !== 'text') {
lastInput = lastInput.previousElementSibling;
}
// and get its value
var lastValue = lastInput ? lastInput.value : null;
The interesting part of this solution is that is create no array, so you save some JavaScript memory.
It should be ok with Firefox, Chrome and IE 9.
Related
I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/
I want to get "The walking dead" also but it only gets the first hidden. Can i put a class on .this or how should I do?
$(".articel input[type='button']").click(function(){
var price = $(this).siblings("input[type='hidden']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
var name = $(this).siblings("input[type='hidden']").attr("value");
var ul = document.getElementById("buylist");
var prod = name + " x " + quantity + " " + price + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
<form class="articel">
Quantity: <input type="number" style="width:25px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30">
<input type="hidden" value="The walking dead">
</form>
The conventional way to identify form fields is by the name property.
HTML:
<input type="hidden" name="title" value="The walking dead">
jQuery:
var name = $(this).siblings('input[name=title]').val();
Your current selector, siblings("input[type='hidden']"), selects all hidden field siblings, but since you have no way to discern them, attr will always just yield the value of the first match.
You could also have iterated over your collection of elements, or accessed them by index siblings('input[type=hidden]:eq(1)') or siblings('input[type=hidden]').eq(1), for instance, but it is a poor design that will break your code if you add another hidden field for something else. You really should prefer to name your elements so that you can access them in a meaningful way and know your data. That way you'll be free to move around and modify your markup according to new requirements, without breaking your script.
By the way, I'm using .val() above, which is shorthand for .attr('value').
One option is to use special selectors, e.g. :first and :last:
var price = $(this).siblings("input[type='hidden']:first").attr("value");
var name = $(this).siblings("input[type='hidden']:last").attr("value");
However, you always can set a class name to the elements:
<input type="hidden" class="price" value="30">
<input type="hidden" class="name" value="The walking dead">
var price = $(this).siblings(".price").attr("value");
var name = $(this).siblings(".name").attr("value");
I would add an class name to your hidden inputs (price, name). This way the html source code is more readable and also the js code will be more readable.
I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.
I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D
I am using ASP.Net MVC along with Jquery to create a page which contains a contact details section which will allow the user to enter different contact details:
<div id='ContactDetails'>
<div class='ContactDetailsEntry'>
<select id="venue_ContactLink_ContactDatas[0]_Type" name="venue.ContactLink.ContactDatas[0].Type">
<option>Email</option>
<option>Phone</option>
<option>Fax</option>
</select>
<input id="venue_ContactLink_ContactDatas[0]_Data" name="venue.ContactLink.ContactDatas[0].Data" type="text" value="" />
</div>
</div>
<p>
<input type="submit" name="SubmitButton" value="AddContact" id='addContact' />
</p>
Pressing the button is supposed to add a templated version of the ContactDetailsEntry classed div to the page. However I also need to ensure that the index of each id is incremented.
I have managed to do this with the following function which is triggered on the click of the button:
function addContactDetails() {
var len = $('#ContactDetails').length;
var content = "<div class='ContactDetailsEntry'>";
content += "<select id='venue_ContactLink_ContactDatas[" + len + "]_Type' name='venue.ContactLink.ContactDatas[" + len + "].Type'><option>Email</option>";
content += "<option>Phone</option>";
content += "<option>Fax</option>";
content += "</select>";
content += "<input id='venue_ContactLink_ContactDatas[" + len + "]_Data' name='venue.ContactLink.ContactDatas[" + len + "].Data' type='text' value='' />";
content += "</div>";
$('#ContactDetails').append(content);
}
This works fine, however if I change the html, I need to change it in two places.
I have considered using clone() to do this but have three problems:
EDIT: I have found answers to questions as shown below:
(is a general problem which I cannot find an answer to) how do I create a selector for the ids which include angled brackets, since jquery uses these for a attribute selector.
EDIT: Answer use \ to escape the brackets i.e. $('#id\\[0\\]')
how do I change the ids within the tree.
EDIT: I have created a function as follows:
function updateAttributes(clone, count) {
var f = clone.find('*').andSelf();
f.each(function (i) {
var s = $(this).attr("id");
if (s != null && s != "") {
s = s.replace(/([^\[]+)\[0\]/, "$1[" + count + "]");
$(this).attr("id", s);
}
});
This appears to work when called with the cloned set and the count of existing versions of that set. It is not ideal as I need to perform the same for name and for attributes. I shall continue to work on this and add an answer when I have one. I'd appreciate any further comments on how I might improve this to be generic for all tags and attributes which asp.net MVC might create.
how do I clone from a template i.e. not from an active fieldset which has data already entered, or return fields to their default values on the cloned set.
You could just name the input field the same for all entries, make the select an input combo and give that a consistent name, so revising your code:
<div id='ContactDetails'>
<div class='ContactDetailsEntry'>
<select id="venue_ContactLink_ContactDatas_Type" name="venue_ContactLink_ContactDatas_Type"><option>Email</option>
<option>Phone</option>
<option>Fax</option>
</select>
<input id="venue_ContactLink_ContactDatas_Data" name="venue_ContactLink_ContactDatas_Data" type="text" value="" />
</div>
</div>
<p>
<input type="submit" name="SubmitButton" value="AddContact" id='addContact'/>
</p>
I'd probably use the Javascript to create the first entry on page ready and then there's only 1 place to revise the HTML.
When you submit, you get two arrays name "venue_ContactLink_ContactDatas_Type" and "venue_ContactLink_ContactDatas_Data" with matching indicies for the contact pairs, i.e.
venue_ContactLink_ContactDatas_Type[0], venue_ContactLink_ContactDatas_Data[0]
venue_ContactLink_ContactDatas_Type[1], venue_ContactLink_ContactDatas_Data[1]
...
venue_ContactLink_ContactDatas_Type[*n*], venue_ContactLink_ContactDatas_Data[*n*]
Hope that's clear.
So, I have a solution which works in my case, but would need some adjustment if other element types are included, or if other attributes are set by with an index included.
I'll answer my questions in turn:
To select an element which includes square brackets in it's attributes escape the square brackets using double back slashes as follows: var clone = $("#contactFields\[0\]").clone();
& 3. Changing the ids in the tree I have implemented with the following function, where clone is the variable clone (in 1) and count is the count of cloned statements.
function updateAttributes(clone, count) {
var attribute = ['id', 'for', 'name'];
var f = clone.find('*').andSelf();
f.each(function(i){
var tag = $(this);
$.each(attribute, function(i, val){
var s = tag.attr(val);
if (s!=null&& s!="")
{
s = s.replace(/([^\[]+)\[0\]/, "$1["+count+"]");
tag.attr(val, s);
}
});
if ($(this)[0].nodeName == 'SELECT')
{ $(this).val(0);}
else
{
$(this).val("");
}
});
}
This may not be the most efficient way or the best, but it does work in my cases I have used it in. The attributes array could be extended if required, and further elements would need to be included in the defaulting action at the end, e.g. for checkboxes.