I'm trying to send multiple input values via AJAX to my PHP script. It's working fine when I use getElementById. However I have the option to add a child. It iterates the input fields, then I get values only from the first child. I tried to use getElementsByClassName but it gives values as undefined. This is my code:
<div id="name-field" class="name-field row">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Name of child</label>
<input id="firstname" class="firstname" name="firstname" type="text" />
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" id="thedate" />
</div>
</div>
</div>
<a href="#" id="addChild" name="addchild" class="btn-success">Add Child</a>
<a href="#" id="stepname" class="btn" onclick="btnSubmit('step1')">Next Step</a>
//Iterate child function
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Sending values function
function btnSubmit(step) {
//Set Var with Name
//Set Var with DoB
if (step == 'step1') {
//values using ID
var Name = document.getElementById("firstname").value;
var DoB = document.getElementById("thedate").value;
//Values using classname
var Name = document.getElementsByClassName("firstname").value;
var DoB = document.getElementsByClassName("date").value;
//Create a Variable catVar Having the Var Name and Var DoB Concatinated with a --
var stepVar = Name + "--" + DoB;
$(".thevoornaam, .date").each(function() {
alert();
});
} else {
}
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", "validations/btnSubmit.php?q=" + step + "&q2=" + stepVar, true);
xmlhttp.send();
}
I hope you guys understand what I'm trying to achieve with this, if I did't explain it correctly.
Thanks in advance.
dateinput hasdateclass name but you are looking forthedate. Also,getElementsByClassNamereturn an array of matched elements so you have to iterate through instead of trying to get.value