how to prevent to change selectbox value if i say no to confirm

后端 未结 4 1452
野趣味
野趣味 2021-02-07 00:59

i m using a select box of country, when user select a country then add branch link appears and user add branches under that country, but when user want to change country then al

相关标签:
4条回答
  • 2021-02-07 01:28

    You can just store the previous value and set it back if needed, like this:

    var countryVal;
    $("#country").change(function() {
      var newVal = $(this).val();
      if (!confirm("Are you sure you wish to destroy these country branches?")) {
        $(this).val(countryVal); //set back
        return;                  //abort!
      }
      //destroy branches
      countryVal = newVal;       //store new value for next time
    });
    

    Or use .data() as @Gaby suggests, like this:

    $("#country").change(function() {
      var newVal = $(this).val();
      if (!confirm("Are you sure you wish to destroy these country branches?")) {
        $(this).val($.data(this, 'val')); //set back
        return;                           //abort!
      }
      //destroy branches
      $.data(this, 'val', newVal);        //store new value for next time
    });
    
    0 讨论(0)
  • 2021-02-07 01:33

    Below solution worked for me. First of all onfocus is called. This event keeps the current value in a attribute "PrvSelectedValue". Secondly onchange is called, we set the previous value if user cancel the confirmation popup.return false is used to prevent the postback in ASP.NET.

    <select   
    onfocus="this.setAttribute('PrvSelectedValue',this.value);" 
    
    onchange="if(confirm('Do you want to change?')==false){ this.value=this.getAttribute('PrvSelectedValue');return false; }" 
    
    ></select>
    
    0 讨论(0)
  • 2021-02-07 01:38

    I'm posting this reply at the risk of ridicule because I'm admittedly pretty noob at this stuff (only been learning a month or two), but I was able to handle a similar situation (changing time zones) just doing this:

    $(".timezonedropdown").change(function() {
        var newVal = $(this).val();
        if(!confirm("Are you sure?")) {
            $(this).val($(this).closest('select').attr("data-originaltimezone"));
        }
    });
    

    Then in my html I included data-originaltimezone="whatever" in the select. I had the class timezonedropdown for the select as well. Hope that helps! :)

    0 讨论(0)
  • 2021-02-07 01:49

    The following is working for me (Chrome). Above not. In case of this.defaultValue, it goes to empty other than default selected text/value.

    if(confirm('sure?')){
        //do sth;
    }else{
        this.selectedIndex = 0; // if cancel the confirm window, option remains as unchanged.
    }
    
    0 讨论(0)
提交回复
热议问题