jquery-editable-select icon indicating copy to clipboard operation
jquery-editable-select copied to clipboard

Using value attribute of <option> tag

Open adl1995 opened this issue 7 years ago • 3 comments

I'm running a Laravel 5.4 application and using jquery-editable-select to create a typeable pulldown. My code is set up like this:

<select id="country_code_dropdown" name="country_code">
    <option value="ZM" >Zambia</option>
    <option value="AL" >Albania</option>
    <option value="DZ" >Algeria</option>
    ...
</select>

Everything is going great, but when the POST request is sent I get the value Albania instead of AL. Is there any way to pass the value attribute?

adl1995 avatar Jun 05 '17 08:06 adl1995

		$('#district').editableSelect('add', function(){
			$(this).val(item.id);
			$(this).text(item.name);
		});

mosleh200989 avatar Jun 28 '17 08:06 mosleh200989

@mosleh200989 what exactly did you mean there? What is item ? What is item.id and name? And how should we use this snippet to get our 2-letter value in this case?

vilmes21 avatar Jul 02 '17 22:07 vilmes21

@adl1995 this happens because the plugin replaces the select element with a text input and a hidden ul list of li items generated using the select options.

What you can do to fix this is change your code like this:

First replace your select html code with this:

<input type="hidden" name="country_code" id="country_code">
<select id="country_code_dropdown">
    <option data-cc="ZM" >Zambia</option>
    <option data-cc="AL" >Albania</option>
    <option data-cc="DZ" >Algeria</option>
    ...
</select>

Then where you included the script tag with the options for your plugin you can use this:

<script type="text/javascript">
	$('#country_code_dropdown').editableSelect({
		... your plugin config options
	}).on('select.editable-select', function (e, el) {
		// el is the selected item "option"
		$('#country_code').val(el.data('cc'));
	});
</script>

What you're doing here is using a hidden input to store the country code value to send it to your php backend using POST, and in your frontend you're using custom "data" attributes in your option items that the plugin will NOT remove from your select, thus being able to manipulate all the data you want with javascript, which is precisely what you're doing. In the javascript when you select an item you get the "data" that you need and assing it value to your hidden field.

I haven't tested this in php but it should work just fine.

leopanzardo avatar Jul 06 '17 21:07 leopanzardo