hi everyone thanks in advance,
I have an HTML form with a div element which has a select tag and two buttons for + and -. The user can click on the + button to duplicate select tag(up to 5 times). I need to store the value from select tag to store in MongoDB using mongoose. I am not sure how I can get this value in JS and store in the variable to pass into MongoDB.
pug file
div(id='divDay1')
button.btnDay1(type='button' onclick='appendRow(this)') +
button.btnDay1(type='button' onclick='removeRow(this)') -
label(for='Day1') Day1:
div
Select#Day1.form-control1(type='select' name='Day1' required='true' )
for task in tasks
option(value=task._id) #{task.TaskName}
// JS code
var x=1;
//Add select list
function appendRow(elem)
{
//get parent node
var parent = elem.parentNode;
//console.log(parent);
//get last child element
var l=parent.lastChild;
//console.log(l);
//var d = document.getElementById(parent.id);
var s = document.getElementById( l.firstChild.id ).cloneNode(true);
s.id = "Select"+x;
//var s1=document.getElementsByClassName("form-control1")
//console.log(d);
//console.log(s);
//Add only 4 child elements
if(l.childElementCount<4){l.appendChild(s);};
//increment x
x++;
};
// remove select list
function removeRow(elem)
{
//alert("JS file Load");
var parent = elem.parentNode;
//get last child element
var l=parent.lastChild;
// remove last child element, Remove upto 1 element
if(l.childElementCount>1){l.removeChild(l.lastChild);};
};
Use this code snippet to get form data in an array
function getSelectValArr() {
var selectValArr = []; $(':input', $('#div1')).not('button').each(function() { selectValArr.push($(this).val());}); return selectValArr;
}
Make sure jQuery has been included in your html.
Then use this array to send data to server.
var setting = {url: 'your_api_url', data: {"someKey": getSelectValArr() }, method: 'POST', success: function(response) {},error: function(error) {}}; $.ajax(setting);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.