1

I'm using a modal, the thing is that I want to change the value of an input field based on it. If modal is open value is "Update" when the modal is not displayed, the value is "create".

I tried like this but since it is executed only one time on page load it's not what I want.

if (($("element").data('bs.modal') || {}).isShown) {
     $('#action-description').val('Update');
} else {
     $('#action-description').val('Create');         
}

And the input field:

<input type="text" id="action-description"  name="action-description" value="">

I need to make something on change so I also tried like this:

$('#modalElement').on('hidden', function(){
    $('#action-description').val('Create');
});

But I can't make it work!

Marc Dix
  • 1,864
  • 15
  • 29
  • 1
    What is the difference between **modal is open** and **modal is not hidden** in the above description? – ismnoiet May 30 '16 at 08:43
  • 1
    What library are you using to show the modal? Most of the modal libraries provide callbacks for open/close event, you can use that. – Tony Dinh May 30 '16 at 08:43
  • Your code should be binded to an event so that it is fired each time. For example to the event that display or hide the modal. – Lelio Faieta May 30 '16 at 08:46
  • I am afraid `$("element").data('bs.modal') || {}` will return a truthy value every time. – Ashish Kumar May 30 '16 at 08:51
  • @hamism sorry I edited my question. –  May 30 '16 at 08:52
  • @TrungDQ I'm using bootstrap modals –  May 30 '16 at 08:52
  • So then you should check http://stackoverflow.com/questions/8363802/bind-a-function-to-twitter-bootstrap-modal-close. – Marc Dix May 30 '16 at 08:56
  • @Egjupss Not sure how you put your code to open the modal, it could be easier if you could provide a JSFiddle to reproduce your problem. It's very helpful for people who trying to help you and sometimes you may resolve the problem by yourself while doing that. – Tony Dinh May 30 '16 at 09:18

1 Answers1

0

Your logic is correct. You can just convert it to a function and open the modal using jquery only.

So, write a function as:

function openModal(){

    $('#myModal').modal('show');

    if (($("element").data('bs.modal') || {}).isShown) {
        $('#action-description').val('Update');
    } 

}

Also you can write a similar function to close the modal on clicking cross or cancel button(if you have any)

function closeModal(){

    $('#myModal').modal('hide');  
    $('#action-description').val('Create'); 
}
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24