user4655002
user4655002

Reputation:

Updating a button id

I am trying to update an id with a value from another button, here's what I have up to now:

$('.viewemployment').on('click', function(e){
    var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + this.id;
    $.get(url,function(d){
            document.getElementById("update_employment").value = this.id;
        },'json');
    }); 

The above is working, because the rest of my code (which I have removed) is working, but the set value isn't. This is the button I am trying to set a value to the id

<button type="button" class="btn btn-default waves-effect update_employment" id="update_employment"  style="display: none;"><?php echo System::translate("Update Employment"); ?></button>

I want to use the id of this button for an ajax request:

    $('.update_employment').on('click', function(e){
        $.ajax({
          url: "<?php echo Config::get('URL'); ?>/dashboard/update_employment/" + $("input[name='json_name']").val() + "/" + 
                $("#json_country").find(":selected").text() + "/" + $("input[name='json_start']").val() + "/" + $("input[name='json_end']").val()
                + "/" + $("input[name='json_duration']").val() + "/" + $("input[name='json_description']").val() + "/" + this.id  + "/" + "<?php echo System::escape(Session::get('token')); ?>",
          cache: false,
          success: function(html){
            <!-- success !-->
          }
        });

but the this.id is being passed as update_employment rather than the new value which shouldv'e been set

Upvotes: 1

Views: 57

Answers (3)

Marcos Dimitrio
Marcos Dimitrio

Reputation: 6852

I don't think it's a good idea to change the id, because you can soon lose track of it as the complexity of you app increases. Instead, you could capture the value of this.id to a variable and store it using jQuery's .data() function:

$('.viewemployment').on('click', function(e){
    var theId = this.id;
    var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + theId;
    $.get(url,function(d){
            $("#update_employment").data("idToQuery", theId);
        },'json');
    }); 

Then access it with:

$("#update_employment").data("idToQuery")

If you really must change the button's id, you can do it through jQuery's .attr() function:

$('#update_employment').attr('id', theId)

Upvotes: 1

Eraph
Eraph

Reputation: 1029

Try changing the following line: document.getElementById("update_employment").value = this.id; to: document.getElementById("update_employment").id = this.id;

Upvotes: 0

Ryan
Ryan

Reputation: 14649

You need to get the target's id from the Event. e is an Event

$('.viewemployment').on('click', function(e){
    var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + this.id;
    $.get(url,function(d){
        document.getElementById("update_employment").value = e.target.id;
    },'json');
}); 

Upvotes: 1

Related Questions