dan dan - 2 months ago 13
Javascript Question

get serialize data from form

I have page like this:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<form id="kelas">
<div class="span12">
<div class="span2">
<input type="text" name="nama_kelas" value="Nama Kelas" style="width: 200px" class="input-block-level">
</div>
<div class="span3">
<span id="simpan_kelas" onclick="simpan_kelas(this)" class="btn btn-success"> Kelas</span>
</div>
</div>
</form>

<script>

function simpan_kelas(elm) {
var nama_kelas = $(elm).prev().val();

if (nama_kelas != "") {
var data = $(elm).parent().serializeArray();
alert("input : "+nama_kelas);
alert("data : "+data);
}
}
</script>


If the input is not empty


  1. The first alert will show the input

  2. The second alert will show data from serialied input



I fail both of them.

Answer

I would probably do it something like this. Since you're using jQuery, it's probably easier (and clearer) to use the click handler provided.

$("#cssSelector").click(function() {
    //do stuff
});

Also, since you're doing jQuery, it's probably more clear to directly get the value of the input element:

$("#cssSelector").val();

The answer provided by @charlietfl would use more of what you've currently got going on. Personally, I'd rather use click handlers and keep my functionality all in a js file (rather than split with onClick stuff in the html).

The final code (linked to above) would look like this:

<form id="kelas">
    <div class="span12">
        <div class="span2">
            <input type="text" name="nama_kelas" value="Nama Kelas" style="width: 200px" class="input-block-level">
        </div>
        <div class="span3">
            <input type="button" id="simpan_kelas" value="Kelas" class="btn btn-success" />
        </div>
    </div>
</form>

$("#simpan_kelas").click(function() {
    var nama_kelas = $("#simpan_kelas").val();

    if (nama_kelas != "") {
        var data = $("#kelas").serializeArray();
        alert("input : "+nama_kelas);
        alert("data : "+data);
    }
});