Avicinnian
Avicinnian

Reputation: 1830

Altering the value of an option (select) element?

I'm attempting to select the selected value of a <select> form element, and append the value with -R. (This will be for regex matching later on). Anyway, so far I've tried the following:

Attempt 1:

var country = $('select[name=g_country\\['+value+'\\]]').val(); 
$('select[name=g_country\\['+value+'\\]]').find('option[value=' + value +']').val(country + '-R');

Attempt 2:

var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').val(country + '-R');

I can tell that the selection of the correct form element (using delete_x, where x is a number) works fine, as the form elements to disable when .select-delete is clicked, however the value setting doesn't. The commented portion down the bottom is what I've been using to check the value of the <select> element post-value change (or what should be post-value change).

Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/11/

Any help/edits/answers will be greatly appreciated!

Upvotes: 1

Views: 157

Answers (2)

gjohn
gjohn

Reputation: 132

Try this:

 $('.select-delete').click( function() {
    var value = $(this).attr('id');
    value = value.replace('delete_', '');

    var country = $('select[name=g_country\\['+value+'\\]] option:selected').val() + '-R';
     alert(country);

    $('select[name=g_country\\['+value+'\\]] option:selected').val(country);

    $('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
    $('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
    $(this).css('display', 'none');
    var check = $('select[name=g_country\\['+value+'\\]]').val();
    $('#test').append(check);
});

There is an issue with your HTML as well.

Upvotes: 1

Avicinnian
Avicinnian

Reputation: 1830

Finally came up with the right selector, props to @gjohn for the idea.

Here's my final working code, that appropriately adds -R to the end of g_country[x]:

$('.select-delete').click( function() {
    var value = $(this).attr('id');
    value = value.replace('delete_', '');

    var country = $('select[name=g_country\\['+value+'\\]]').val();
    $('select[name=g_country\\['+value+'\\]] > option:selected').val(country + '-R');

    $('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
    $('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
    $(this).css('display', 'none');
});

Upvotes: 0

Related Questions