Reputation: 633
In my html template, I have a set of options in a <select>
tag. One particular option allows you to type in custom category name in the input text field.
Now once I click on the submit button, I am unable to fetch the value within the input field (if a value was entered in it).
Here are the HTML <select>
and <input>
field(s):
{% for index in list %}
<select name="browser" id="select_id{{index}}" onchange="if(this.options[this.selectedIndex].value=='customOption'){toggleField(this,this.nextSibling); this.selectedIndex='0';}">
<option value="0">---- select ----</option>
<option value="customOption">[enter your own custom category]</option>
<option value="Chrome">Chrome</option>
<option value="Firefox">Firefox</option>
<option value="Internet Explorer">Internet Explorer</option>
<input name="browser" id="input_id{{index}}" type="text" disabled="disabled" onblur="if(this.value==''){toggleField(this,this.previousSibling);}">
</select>
<!-- SUBMIT BUTTON TO INVOKE add_category() javascript method -->
<button type="button" onclick="add_category('select_id{{index}}', 'input_id{{index}}');">SUBMIT</button>
{% endfor %}
In the add_category()
, I simply want to display the selected/typed in category value as an alert message on the screen.
function add_category(select_id, input_id){
if($("#"+select_id).val()=='0')
{
alert("Please select a valid category");
}
else if($("#"+select_id).val()=='customOption')
{
var i = $("#"+input_id).val();
alert("INPUT CATEGORY: ", i);
}
else
{
var s = $("#"+select_id).val();
alert("SELECTED CATEGORY: ", s);
}
}
However, no value is returned in the input or selected category value.
Upvotes: 0
Views: 349
Reputation: 421
input inside select is not a valid html as Andrian said. You have to create a custom dropdown with input inside, not using the default select but element like ul, li for example.
Upvotes: 0
Reputation: 1930
You can retrieve the value of the select using the below snippet , This would help you.
var mySelect = $('select[name=browser');
var conceptName = mySelect.find(":selected").text();
console.log(conceptName)
The Executable snippet is in the below code Pen URL https://codepen.io/redhatvicky/pen/RdzEGW
Upvotes: 2
Reputation: 21628
This is not even valid html, Chrome renders the input outside of the select.
Place the input outside of the select.
<select>
<option>Select</option>
<input type="text">
</select>
Upvotes: 0
Reputation: 1636
function add_category(select_id, input_id){
if($("#"+select_id+"").val()=='0')
{
alert("Please select a valid category");
}
else if($("#"+select_id+"").val()=='customOption')
{
var i = $("#"+input_id+"").val();
alert("INPUT CATEGORY: ,"+i);
}
else
{
var s = $("#"+select_id+"").val();
alert("SELECTED CATEGORY: ,"+ s);
}
}
});
Upvotes: 0