Reputation: 1234
Knowing just the field name is there any way to get the value in such a way that is compatible with text, textarea and radio button.
Either using native javascript or the jQuery library
I can use $("input[name='field1']").val()
but it doesn't work with radio buttons or i can use $("input[name='field1']:checked").val()
but it only works with radio buttons. I know I can add logic that tries to determine the field type but starts getting complicated as you accommodate more types of fields.
Below is a more concrete example of what I am trying to do:
<form>
<label><input type="radio" name="field1" value="a" /> a</label>
<label><input type="radio" name="field1" value="b" /> b</label>
<input type="text" name="field2" />
<button type="button">Test</button>
</form>
<script>
getFieldValue = function(name1) {
return $("input[name='" + name1 + "']").val(); //doesn't work with radio buttons
}
$('button').click( function() {
alert(getFieldValue('field1'));
});
</script>
Update 5/26/2017 Ended up using the jQuery serializeArray function. Below is my code in case anyone is curious (https://jsfiddle.net/t6p8sqLu/2/)
var formdata = $("form").serializeArray();
function getFieldValue(name) {
var result = [];
for (var x in formdata) {
if (formdata[x].name === name) {
result.push(formdata[x].value);
}
}
return result;
}
Upvotes: 0
Views: 3866
Reputation: 11
I've been using this function for years, and it works
function getValueForm(id, return_num){
var value = "";
if($("#"+id).is(":checkbox")){
value = ($("#"+id).is(':checked'))?"1":"";
}else{
value = $("#"+id).val();
}
if(value === null){
value = "";
}
return_num = (return_num === undefined)?false:return_num;
if(return_num){
if(value === ""){
value = 0;
}else{
value = parseFloat(value);
}
}
return value;
}
Upvotes: -1
Reputation: 3832
The answer to the OP's question as it pertains to JavaScript is that unless you're able to use a browser compatible with the FormData object and its methods, the answer is then likely probably not unless you can iterate through FormData using the "for(var p of iterable)" syntax.
So, here's one way to automate retrieving the values of a form containing traditional inputs with JavaScript. Note, the custom function showNameValue() works with all the inputs the same way. But, the event listener treats controls differently since the radio buttons and checkboxes need to be inspected for having been checked while the text input and textarea need to be evaluated for whether there is any discernible content.
function showNameValue(obj) {
var arr = [ obj.name, obj.value ];
console.log( arr.join(": ") );
}
var d = document;
var btn = d.getElementsByTagName("button")[0];
var e = d.forms[0].elements;
var f = null; // field
btn.addEventListener("click", function() {
for (var i = 0, max = e.length; i < max; i++) {
f = e[i];
switch (f.type) {
case "radio":
if (f.checked) {
showNameValue(f);
}
break;
case "checkbox":
if (f.checked) {
showNameValue(f);
}
break;
case "textarea":
if (f.value = f.value.trim()) {
showNameValue(f);
}
break;
case "text":
if (f.value = f.value.trim()) {
showNameValue(f);
}
break;
}
} //end for
}); // end event listener
See demo
Note, though the textarea HTML tag does not have an explicit type attribute, the DOM Textarea object (see here) possesses such a property, so JavaScript can detect its value. Also, trimming text and textarea values matters because empty space may precede or follow these values due to space, newline or tab characters.
Upvotes: 0
Reputation: 1554
If you are using a form with name
and all input fields with name
, then you might want to use jQuery('form[name="xyz"]').serializeArray()
.
Jquery Serialize // always returns string
Or you can always use jquery pseudo selector
$(":input").each(function() {
if ($(this).attr('type') === 'radio' && !$(this).prop('checked')) {
return;
}
console.log($(this).attr('name'), $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
input text:
<input type="text" name="name1" value="Name" /><br/>
Checkbox
<input type="checkbox" name="check1" value="yes" checked /> Yes
<input type="checkbox" name="check1" value="all" checked /> Yes to all<br/>
Radio
<input type="radio" name="radio1" value="yes" checked />
<input type="radio" name="radio1" value="no" /><br/>
Textarea
<textarea name="textarea">Textarea</textarea><br/>
Select
<select name="select1">
<option value="dummy" selected>Dummy</option>
</select>
</form>
Upvotes: 1
Reputation: 1234
After a bit of digging found the native FormData construct works nicely and can accommodate all input types
Ultimately it is the following code
(new FormData(document.querySelector("form"))).getAll(name).join(',');
Full Test Code
<form>
<div>
<label><input type="radio" name="field1" value="a" /> a</label>
<label><input type="radio" name="field1" value="b" /> b</label>
</div>
<div>
<input type="text" name="field2" />
</div>
<div>
<textarea name="field3"></textarea>
</div>
<div>
<input type="checkbox" name="field4" value="x" /> x
<input type="checkbox" name="field4" value="y" /> y
</div>
<button type="button">Test</button>
</form>
<script>
function getFieldValue(name) {
return (new FormData(document.querySelector("form"))).getAll(name).join(',');
}
$('button').click( function() {
alert('field1:' + getFieldValue('field1'));
alert('field2:' + getFieldValue('field2'));
alert('field3:' + getFieldValue('field3'));
alert('field4:' + getFieldValue('field4'));
});
</script>
Upvotes: 1