philburns
philburns

Reputation: 330

How to set Bootstrap modal button attribute by JavaScript

I have two Bootstrap buttons in a Grails application triggering similar functions, each opening the same modal to ask the user to enter credentials:

<button type="button" class="btn btn-success" data-toggle="modal" mykey="postcard" data-target="#credentialsModal">Send a postcard</button>
<button type="button" class="btn btn-success" data-toggle="modal" mykey="letter" data-target="#credentialsModal">Send a letter</button>
<div class="modal fade" id="credentialsModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Please enter your credentials</h4>
      </div>
      <div class="modal-body">
        <g:form>
          <div class="input-group">
            <span class="input-group-addon">User</span>
            <g:textField name="myUsername" size="24" class="form-control" />
          </div>
          <div class="input-group">
            <span class="input-group-addon">Password</span>
            <g:textField name="myPassword" size="24" class="form-control" />
          </div>
          <div align="right">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <g:actionSubmit action="" value="Send" class="btn btn-success" name="cred-modal-btn-send" data-toggle="tooltip" data-placement="top" title="Enable JavaScript" />
          </div>
        </g:form>
      </div>
    </div>
  </div>
</div>
<script>
  $('#credentialsModal').on('show.bs.modal', function (event) {
    var key = $(event.relatedTarget)[0].getAttribute("mykey");
    if (key.localeCompare('postcard') == 0){
        $(this).find('.modal-body .cred-modal-btn-send').attr('action', 'sendPostcard');
        $(this).find('.modal-body .cred-modal-btn-send').attr('name', '_action_sendPostcard');
    }
    else if (key.localeCompare('letter') == 0){
        $(this).find('.modal-body .cred-modal-btn-send').attr('action', 'sendLetter');
        $(this).find('.modal-body .cred-modal-btn-send').attr('name', '_action_sendLetter');
    }
  })
</script>

Problem is: my attempt to address the button's attributes with $(this).find('.modal-body .cred-modal-btn-send').attr(...) fails. The rendered HTML still shows the original attribute values, unmodified by the script. I've checked that I do address the modal by $(this).find('.modal-body'). What's wrong here?

Upvotes: 1

Views: 2069

Answers (1)

StaticBeagle
StaticBeagle

Reputation: 5175

There is no button with class="cred-modal-btn-send" inside the modal body, that's why the selector '.modal-body .cred-modal-btn-send' fails. You could use

$(this).find('.modal-body .btn.btn-default').attr(...)

to select the button inside the modal.

Upvotes: 2

Related Questions