简体   繁体   中英

How can I take contents of one element and add to another when they both have an id ending in the same two or three digit number?

I have this code:

$('.update-title')
    .change(function () {
        $(this).prop('title', $('option:selected', this).prop('title'));
    });

and this HTML:

<select id="modal_TempRowKey_14" class="update-grid update-title">
...
...
</select>

<input id="modal_Title_14" class="update-grid" type="text" value="xx">

Is it possible for me to make it so that when the .update-title changes then the value of the title is put into the input id with the matching number. So in this case the #modal_TempRowKey_14 title would go into #modal_Title_14 value

Important

I want this to happen only if the element being changed starts with modal_TempRowKey . Is this possible to put into the change block?

Try

$('.update-title').on("change", function() {
    var id = this.id.replace('modal_TempRowKey_', '');  
    $("#modal_Title_" + id).val( $(this).val() );
});

My suggestion, rather than trying to parse id attributes, is to make use of jQuery's data function.

Edit your HTML so that the select menu has a data-target attribute:

<select id="modal_TempRowKey_14" data-target="#modal_Title_14" class="update-grid update-title">
...
...
</select>

Then, create your event handler like so:

$('.update-title').on('change',function() {
    var $this = $(this);
    $($this.data('target')).val($this.val());
})

You use the data-target attribute to find the element to which you want to apply the select menu's value.

Here's a demo:

--- jsFiddle DEMO ---

$('.update-title').change(function () {
    var m = this.id.match(/^modal_TempRowKey_(\d+)$/);
    if (m) {
        $("#modal_Title_" + m[1]).val(this.id);
    }
});​

DEMO .

Others have a more elegant approach, here is my attempt:

http://jsfiddle.net/8sLCL/1/

$('.update-title')
    .change(function () {
        var my_text = $(this).find(":selected").text();
        var my_id = $(this).attr("id");
        var my_num_pos = my_id.lastIndexOf("_");
        var my_num = my_id.substr(my_num_pos + 1 ,my_id.length - my_num_pos  );
        $( "#modal_Title_" + my_num ).val(my_text );
});​

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM