I have this code wherein the button will only enable when a particular input field has a value, when the search button is clicked the last name will remain on the input field, but everytime i clicked the search button, the clear button doesn't detect that there's a value in the input field that's why it was disabled unless you update the text inside the input field. Thank you
<input type="text" id="lastname" name="Last_Name" value="<?php if(isset($_POST['search'])) {echo
$_POST['Last_Name'];} ?>" required>
<button type="submit" name="search">Search</button>
<button type="submit" id="clear">Clear</button>
This is the script
$(document).ready(function(){
$('#clear').attr('disabled',true);
$('#lastname').keyup(function(){
if($(this).val().length !=0)
$('#clear').attr('disabled', false);
else
$('#clear').attr('enable',true);
})
});
CodePudding user response:
$(document).ready(function(){
$('#clear').attr('disabled',true);
$('#lastname').keyup(function(){
if($(this).val().length !=0)
$('#clear').attr('disabled', false);
else
$('#clear').attr('disabled',true);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" id="lastname" name="Last_Name" value="<?php if(isset($_POST['search'])) {echo $_POST['Last_Name'];} ?>" required>
<button type="submit" name="search">Search</button>
<button type="submit" id="clear">Clear</button>
CodePudding user response:
Does it help if you do it like in the following example ?
const updateClearButtonState = () => {
const isLastNameEmpty = $('#lastname').val().length === 0;
$('#clear').attr('disabled', isLastNameEmpty);
};
$(document).ready(function(){
$('#lastname').keyup(updateClearButtonState);
updateClearButtonState();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" id="lastname" name="Last_Name" value="<?php if(isset($_POST['search'])) {echo $_POST['Last_Name'];} ?>" required>
<button type="submit" name="search">Search</button>
<button type="submit" id="clear">Clear</button>
The difference with your solution, is that I moved functionality of changing clear
button state to a separate function.
And then I call that function immediately when document
is ready.
This way the clear
button should receive the correct initial state.