Advanced use of jQuery serializeArray() - javascript

I'm currently submitting a form via ajax and pass in a manually created data variable that looks a bit like this:
var data = 'answer1='
+ $("input[name=question_1]:checked").val()
+ '&q1_option=' + $("input[name=question_1]:checked").attr("id")
This continues throughout the list of form elements obviously increasing incrementally question_2, question_3 etc. The problem is that this is a bit messy. I'd like to use jQuery serializeArray but, to do this I would need to pass in an extra parameter. I need to pass the input value and the input id as this id is used in the data.
Is there a way I can achieve this using jQuery serializeArray()?
Example form markup:
<label>What is your gender?<span class="required"> *</span></label>
<input id="1" type="radio" name="question_1" value="Male"><label class="standard" for="1">Male</label><br>
<input id="2" type="radio" name="question_1" value="Female"><label class="standard" for="2">Female</label><br>
<label>How old are you?<span class="required"> *</span></label>
<input id="3" type="radio" name="question_2" value="Under 25"><label class="standard" for="3">Under 25</label<br>
<input id="4" type="radio" name="question_2" value="25-29"><label class="standard" for="4">25-29</label><br>
<input id="5" type="radio" name="question_2" value="30-39"><label class="standard" for="5">30-39</label><br>
<input id="6" type="radio" name="question_2" value="40-49"><label class="standard" for="6">40-49</label><br>
<input id="7" type="radio" name="question_2" value="50-59"><label class="standard" for="7">50-59</label><br>
<input id="8" type="radio" name="question_2" value="60+"><label class="standard" for="8">60+</label><br>

First of all, let me point out that this looks like a misuse of forms. If the name of the form element would be "answer1" instead of "question_1", and if your options would be named "q1_option" rather than "question_1", and if you accessed their values rather than their ids, you would be able to serialize the form in a simple one-liner, and, essentially, this is the meaning that name and value are intended to convey.
Having said that, $.serializeArray yields an array of key/value pairs. It's hard to see what you would want $.serializeArray to do in your specific scenario. If you want such an array, you could construct it yourself:
var keyValuePairs = [];
keyValuePairs.push({ name: 'answer1', value: $('input[name=question_1]:checked').val() })
var options = $('input[name^="question_"]:checked');
for(var i = 0; l = options.length; i < l; i++) {
keyValuePairs.push({
name: 'q' + i + '_option',
value: options.get(i).attr('id')
});
}
Given such an array, you could serialize it to a string like the one in your example, using
var data = $.param(keyValuePairs);

Related

Jquery should return one array of data from form, returns two

I'm working with a form of radio buttons and arrays using Jquery, but I am having trouble recording the selected values into one array. Here's my code:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
//do other stuff with it later
});
});
});
</script>
<form>
<fieldset id="group1">
<div>
<input type="radio" id="r1" name="group1"" value="STEM">
<label for="r1"> STEM (Science, Tech, Engineering and Math)</label>
</div>
<div>
<input type="radio" id="r2" name="group1"" value="HUMAN">
<label for="r2">Humanities (Art, History, Music, Language) </label>
</div>
</fieldset>
<fieldset id="group2">
<div>
<input type="radio" id="r3" name="group2" value="EXTRO">
<label for="r3"> Extrovert (Like being around other people)</label>
</div>
<div>
<input type="radio" id="r4" name="group2" value="INTRO">
<label for="r4">Introvert (Don't like being around other people)</label>
</div>
</fieldset>
</form>
<button id="submit" type="button" value="Submit">Submit</button>
I would like to to output into one array, but currently it outputs into an array for every fieldset, how do I fix this?
Ciao.
Maybe I don't understand the question correctly but it seems like the output of the function is an array of objects, [{name: 'group1', value: ...}, {name: 'group2', value: ...}]
So, if you just want the values only in one array, this seems like will do the job.
var x = $("form").serializeArray().map((ob) => ob.value);
(I wanted to ask details but I can't comment since I don't have enough reputation... hope it helps.)

How to get custom attribute value in jquery or JS from radio buttons?

I got a piece of HTML:
<input type="radio" name="radioBtn" onChange="rdbtn()" value="100" isprm="true">
<input type="radio" name="radioBtn" onChange="rdbtn()" value="110" isprm="true">
and I want to pass the custom attribute value into a variable. Here is what I tried and does not work:
function rdbtn(){
var radioVal = $(this).val();
var radioPRM = $("input[id=radioVal]:checked").attr('isprm');
...
}
and
$('input[id=radioVal]').data("isprm");
No luck. Do you have any ideas how to make it work? Thanks.
Firstly, isprm is not a valid attribute so your HTML is invalid. If you need to store ancillary data with an element use a data-* attribute:
<input type="radio" name="radioBtn" onChange="rdbtn()" value="100" data-isprm="true">
<input type="radio" name="radioBtn" onChange="rdbtn()" value="110" data-isprm="true">
You can then use data() to retrieve the value:
var radioPRM = $('input[name="radioBtn"]:checked').data('isprm');
You need to prefix data- with custom attributes to work with .data(). Also you have to use name when using attribute value selector since you have not specified id of radio option and use name which you have specified i.e. radioBtn
Use
<input type="radio" name="radioBtn" onChange="rdbtn()" value="110" data-isprm="true">
Then
$('input[name=radioBtn]').data("isprm");
DEMO

Remove from ... to

So I have a kind of problem: I need to remove "information" from tag to tag including text between it.
So somewhere in html is:
<input type="radio" rel="1" value="Surname1" name="lastnames">Surname1<br>
<input type="radio" rel="2" value="Name2" name="lastnames">Name2<br>
<input type="radio" rel="3" value="lol" name="lastnames">lol<br>
<input type="radio" rel="4" value="lol2" name="lastnames">lol2<br>
And for example:
var current_id = $('input:checked:radio').attr('rel');
$.get('index.php?delete_by_id='+current_id);
$("input:radio[rel='"+current_id+"']").remove();
So, after the GET to php is sent, I need to delete from the radio list deleted item. With input all ok, but with name next to him I have problems...
PS.
I know, that situation is stupid, but I don't have any time to rewrite it until tomorrow (exams)
Wrap the label with a span element.
<input type="radio" rel="1" value="Surname1" name="lastnames"><span>Surname1</span><br>
<input type="radio" rel="2" value="Name2" name="lastnames"><span>Name2</span><br>
Then while deleting, Get the next span and remove it as well
var item=$('input:checked:radio');
var current_id = item.attr('rel');
$.get('index.php?delete_by_id='+current_id,function(data){
item.remove();
item.next("span").remove();
});
It is always a good practice to keep HttpPost Operations for Delete/Update functions. Otherwise anybody can delete a record from your database if they know the item id, by simply executing your page with those querystrings in the browser.
Not sure exactly what you are trying to do and/or why it is not working, but consider writing the code like this:
var $selected_radio = $('input:radio:checked'); // store element reference
$.get('index.php?delete_by_id=' + $selected_radio.attr('rel'), function() {
// use a callback function to only remove if code succeeds
$selected_radio.remove();
});
EDIT: Looking back I see you want to remove the input along with its label. You just need to fix your HTML to be what it actually should be:
<label>
<input type="radio" rel="1" value="Surname1" name="lastnames"> Surname1
</label>
Which then makes the remove code in jQuery look like:
$selected_radio.closest('label').remove();
I ussually always use a label, to show text that is connected to a radio button:
<input id="radio1" type="radio" rel="1" value="Surname1" name="lastnames"><label for="radio1">Surname1</label><br>
<input id="radio2" type="radio" rel="2" value="Name2" name="lastnames"><label for="radio2>Name2</label><br>
<input id="radio3" type="radio" rel="3" value="lol" name="lastnames"><label for="radio3">lol</label><br>
<input id="radio4" type="radio" rel="4" value="lol2" name="lastnames"><label for="radio4">lol2</label><br>
Then you can do like this in your javascript code:
var current_rel = $('input:checked:radio').attr('rel'),
current_id = $('input:checked:radio').attr('id');
$.get('index.php?delete_by_id='+current_rel);
$('#' + current_id + ', label[for="' + current_id + '"]).remove();

AJAX multiple checkboxes / multiselect

Alrighty then, howdy first off; quick question I have a form that has multiple check boxes with the same name (i.e. -
<input type="checkbox" name="myname[]" value="1" />
<input type="checkbox" name="myname[]" value="1" />
<input type="checkbox" name="myname[]" value="2" />
<input type="checkbox" name="myname[]" value="3" />
<input type="checkbox" name="myname[]" value="4" />
)
I am not using JQuery as I don't need that much baggage it is a very simple script that does does what is says on the tin, just serialize a form for use in an ajax post request. I would like to know though how to serialize the multiple checkboxes above for correct use in php.
I think the easiest way would be to grab all the checkboxes with document.getElementsByName and loop to get what's checked.
var checkedValues = [];
var allCheckboxes = document.getElementsByName("myname[]");
for(var i = 0; i < allCheckboxes.length; i++){
if (allCheckboxes[i].checked)
checkedValues.push(allCheckboxes[i].value);
}
I assume PHP can treat a comma-delimited list of values as an array:
checkedValues.join(); //tested and produces ---> 0,3,4

realtime update text in javascript by same id

How do I update the text in the id="b"?
<script type="text/javascript">
function updateb()
{
var a= document.getElementById("a").value;
var b = document.getElementById("b").innerHTML = a * 10;
}
</script>
<input type="text" id="a" name="a" value="10" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="20" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="30" onKeyUp="updateb();" /><p id="b" name="b"></p>
1.) IDs should be always unique in a page.
2.) GetElementById always returns only one element with same id if there are multiple ids with same value
3.) for above question you can try getElementsByName. it is quite similar to getElementById with a diff that it will give u all elements with same name. if you do
x= document.getElementsByName("b");
x[0] will contain first one
x[1] will contain 2nd one
x[2] will contain 3rd one
If you want it be done by getElementById then change ur elements id with any other unique name like:
<script type="text/javascript">
function updateb(Src)
{
var a= Src.value;
document.getElementById("b" + Src.id.substr(1)).innerHTML = a * 10;
}
</script>
<input type="text" id="a1" name="a" value="10" onKeyUp="updateb(this);" /><p id="b1" name="b"></p>
<input type="text" id="a2" name="a" value="20" onKeyUp="updateb(this);" /><p id="b2" name="b"></p>
<input type="text" id="a3" name="a" value="30" onKeyUp="updateb(this);" /><p id="b3" name="b"></p>
Note that an id field must be unique to a document. That is, you can't have three elements with the same ID as in your example.
Otherwise, the code you posted should update the contents of B, though obviously you'd need to do this in response to an onchange or onblur event on the input field.
As others have pointed out, all elements in a document should have a unique id.
In your case, however, an id may not be required at all, as you can use the relative positions of elements to achieve your aims.
This example doesn't need an id or a name, but this may differ in your case, depending on your overall requirements.
<script type="text/javascript">
function updateb(inputElement)
{
var a = inputElement.value;
var target = inputElement.nextSibling;
if(target != null){
target.innerHTML = a * 10;
}
}
</script>
<input type="text" value="10" onKeyUp="updateb(this);" /><p></p>
<input type="text" value="20" onKeyUp="updateb(this);" /><p></p>
<input type="text" value="30" onKeyUp="updateb(this);" /><p></p>
Using a solution like the one offered by #KoolKabin may be better in the long run, as it is more tolerant to changes in the HTML structure. Either way, there are usually several different ways to approach any given problem, and you should evaluate the best for the circumstances.

Categories

Resources