简体   繁体   中英

Jquery updating link with href value

I have the following code

jQuery(document).ready(function($)
{
  $("#deleteorderb").click(function()
  {
    $("#deleteorder").attr('href','/deleteorder.php?id=' + $('#deleteorderb').val());
  })
});
<a onclick="jQuery('#modal-2').modal('show');" id="deleteorderb" name="deleteorderb" 
   value="<?php echo $r['id']; ?>" class="btn btn-danger btn-sm btn-icon icon-left">
     Cancel
</a>

When I click the link, it opens a popup modal, which has a but of text saying are you sure you want to delete, and then there's a link, herf, I want to update that herf to equal the the other href's value which will be a database query to get the id. the ink updates with the above but not the id. I have checked the source code and the a hrefs value IS set.

You want to grab element attribute value, so instead of

$('#deleteorderb').val()

try

$('#deleteorderb').attr('value')

Try something like this, *note the use of .attr("value") not .val():

<a onclick="dialog();" id="deleteorderb" name="deleteorderb" value="<?php echo $r['id']; ?>" class="btn btn-danger btn-sm btn-icon icon-left"> Cancel</a>
<script>
    $(document).ready(function() {
        $("#deleteorderb").click(function() {
            var a = $('#deleteorderb').attr("value");
            var link = "/deleteorder.php?id=" + a;
            $("#deleteorder").attr("href", link);
        });
        function dialog() {
            $('#modal-2').modal('show');
        };
    });
</script>

The value attribute is normally used on form fields. So in your case it would make sense to use a data attribute as follows:

<a  id="deleteorderb" name="deleteorderb" data-value="<?php echo $r['id']; ?>" .....

And in your JavaScript you could access it like so:

$('#deleteorderb').data('value');

BONUS

I would not recommend using inline JS. Instead just use jQuery to setup a click event listener in your DM ready callback:

$('#deleteorderb').on('click', function( e ) {
    e.preventDefault();
    $('#modal-2').modal('show');
});

Updated html:

<a 
    id="deleteorderb" 
    name="deleteorderb" 
    data-value="<?php echo $r['id']; ?>" 
    class="btn btn-danger btn-sm btn-icon icon-left">
        Cancel
</a>

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