Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jake White
Jake White
41,730 Points

Input and Select with same name

I am working on web app that submits proposals. The client wants the user submitting the proposal to automatically be a requestor and have the option of adding additional requestors. I was hoping to do something like this <input name="requestor[]" value="1"><select name="requestor[]"><option value="2">Jane</option></select>

In testing, I am trying to log the name[] value to the console, but I only get a result of 1, even though I have selected the option in. I was hoping to get a result of 1,2

Is this not possible? If it is, how do I get the value of name[]?

Doing $("*[name='requestor']").val() still just logs 1

1 Answer

I have made a sample code below. I'm not so sure if this is what you want. feel free to try it.

<input name="requestor" id="requestor" value="1">
<select name="requestor1" id="requestir1" onchange="myFunction()">
<option value="0">ADD REQUESTOR</option>
<option value="2">Jane</option>
</select>
var requestor = document.getElementByID("requestor").value;
var requestorTotal =  new Array(requestor);
function myFunction()
{

    var requestor1 = document.getElementByID("requestor1").value;
    requestorTotal.push(requestor1);
    console.log(requestorTotal[0]);
}
Jake White
Jake White
41,730 Points

Thanks! That didn't quite solve it, but it led me on the right track. I ended up doing this

function requestor_combine(){
    var requestor = document.getElementById("requestor").value;
    var requestorTotal =  new Array(requestor);
    var requestor_select = document.getElementById("requestor-select").value;
    if(requestor_select != ""){
        requestorTotal.push(requestor_select);
    }
    return requestorTotal;
}

$(document).on("click", "#save-for-later", function(e){
  e.preventDefault();
  var requestor = requestor_combine();
  console.log(requestor);
});

With how I am doing this, I needed to move the establishment of the requestorTotal array into the function itself because every the "Save for Later" button was clicked, it would add the ids from the select multiple times. Putting it into the function basically reset it every time.