Anonymous Anonymous - 5 months ago 7
jQuery Question

JavaScript if else works like checkbox always in initial state

I can receive a checkbox (blackbox) state like true or false in the browser developer console correctly with

$("#blackbox").prop('checked')
or with
$('#blackbox').is(':checked')
. Tried both.

Let's say I use
checked
in checkbox
<input type="checkbox" id="blackbox" name="blackbox" title="Enable Something" checked>


I'll get longform output both with checkbox checked and unchecked. Same happens with empty checkbox
<input type="checkbox" id="blackbox" name="blackbox" title="Enable Something">
, all I can get in the end is short data output both with checked and unchecked checkbox.

What I really want is long output when the checkbox is checked and short output when the checkbox is unchecked.

<div class="container">
<form action="add" id="urlform" method="POST" accept-charset="utf-8">
<div class="control-group">
<div class="input-append">
<input type="checkbox" id="blackbox" name="blackbox" title="Enable Something">
<input type="text" id="url" value="" placeholder="Text">
<input class="btn btn-warning "type="submit" value="Shorten">
</div>
</div>
</form>
</div>
<form action="/s/add" id="longform" method="POST" accept-charset="utf-8"></form>
<script>
var form = $('#urlform');
var form2 = $('#longform');

if ($('#blackbox').is(':checked')) {
test = form2;
} else {
test = form;
}
form.submit(function () {
$.ajax({
type: test.attr('method'),
url: test.attr('action') + '?url=' + $('#url').val(),
success: function (data) {
test.append('<p style="color:#FFA500">' + 'https://' + location.host + '/' +
data[0].uid + '</p>')
}
});
return false;
});
</script>

Tom Tom
Answer

The if ($('#blackbox').is(':checked')) { ... } is happening on page load and the form.submit is happening multiple times but only using the value that was set on page load.

Move the logic into the form.submit() action:

<script>
  var form = $('#urlform');
  var form2 = $('#longform');

  form.submit(function () {
    if ($('#blackbox').is(':checked')) {
      test = form2;
    } else {
      test = form;
    }
    $.ajax({
        type: test.attr('method'),
        url: test.attr('action') + '?url=' + $('#url').val(),
        success: function (data) {
          test.append('<p style="color:#FFA500">' + 'https://' + location.host + '/' +
          data[0].uid + '</p>')
        }
    });
    return false;
  });
</script>
Comments