Andrey Shandrov Andrey Shandrov - 1 month ago 17
jQuery Question

How to clear input value after first letter?

I want to clear all character after the first letters in the values of inputs using jQuery. I have this:

<form id="form">
<label><input type="checkbox" name="checkbox-one[]" value="A some text">A some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="B some text">B some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="C some text">C some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="D some text">D some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="Е some text">Е some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="F some text">F some text</label>

<input type="submit" value="submit">
</form>


I want the result to be this:

<form id="form">
<label><input type="checkbox" name="checkbox-one[]" value="A">A some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="B">B some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="C">C some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="D">D some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="Е">Е some text</label>
<label><input type="checkbox" name="checkbox-one[]" value="F">F some text</label>

<input type="submit" value="submit">
</form>


How can I do it?

Answer

You can achieve this by providing a function to val() which returns only the first character of the current value:

$('input[type="checkbox"]').val(function(i, v) {
  return v[0];
})

// just to show it works:
$('input[type="checkbox"]').each(function() {
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
    <label><input type="checkbox" name="checkbox-one[]" value="A some text">A some text</label>
    <label><input type="checkbox" name="checkbox-one[]" value="B some text">B some text</label>
    <label><input type="checkbox" name="checkbox-one[]" value="C some text">C some text</label>
    <label><input type="checkbox" name="checkbox-one[]" value="D some text">D some text</label>
    <label><input type="checkbox" name="checkbox-one[]" value="Е some text">Е some text</label>
    <label><input type="checkbox" name="checkbox-one[]" value="F some text">F some text</label>

    <input type="submit" value="submit">
</form>

However, it would arguably be better to do this in your code which populates the form source. This way the user will never see what the values were (assuming that's important to your logic). Using JS means that they will still be able to see the values that were originally loaded in the source of the page.