.preventDefault() no longer functioning as should - javascript

I have got to be missing something simple. This script was functioning as anticipated until I added a new element to toggle the input box with a button in the nav bar. Now the form will redirect on submission.
The behaviour expected is that when input is submitted it appears as a comment underneath the comment box.
Currently my .preventDefault(); is no longer working on the click as I am being redirected. I have put too many hours into trying to figure out what went wrong and need some insight on what I changed or implemented incorrectly.
$(function () {
//Toggle compose input box
$(".compose").click(function () {
event.preventDefault();
$(".new").slideToggle("slow");
textarea.focus()
})
//compose input to comment
$('.Form').on('submit', function (event) {
event.preventDefault();
// 1. Grab the content of the form
let formData = $('.Form').serialize();
let entry = $('.textarea input').val();
console.log(entry)
if (entry === null || entry === '') {
alert('text too short!')
} if (entry.length > 140) {
alert('text too long!')
} else {
// 2. Submit using ajax
$.ajax('/comments', {
method: 'POST',
data: formData,
}).then(function (success) {
console.log('succesful')
// 4. Make sure the new comments shows
return $.ajax('/comments');
}).then(renderComments());
}
});
});
Html:
<main class="container">
<section class="new">
<form action='/comments' Method='POST' id="Form">
<h2>Compose Comment</h2>
<textarea id="textarea" name="text" onfocus='this.select()' placeholder="What are you humming about?"></textarea>
<input class="submit" type="submit" value="Submit">
<span class="counter">140</span>
</form>
</section>

Your form has id="Form", but you are selecting class with jQuery.
i.e you need:
//compose input to comment
$('#Form').on('submit', function(event) {
event.preventDefault();
}
Be careful, serializing logic is using class also, update your references.

//Toggle compose input box
$( ".compose" ).click(function() {
event.preventDefault();
$( ".new" ).slideToggle( "slow" );
textarea.focus()
})
You are not passing the 'event' parameter in this binding as shown below in order to get preventDefault to function appropriately.
//Toggle compose input box
$( ".compose" ).click(function(event) {
event.preventDefault();
$( ".new" ).slideToggle( "slow" );
textarea.focus()
})

Related

jQuery: How to enable/disable button based on input value?

I'm playing around with jQuery and was wondering how you would enable a button once the user has typed into the input field? and if they delete the contents of the input field then the button will be disabled again.
I've created this little demo to help.
Would I have to use 'keyup' to do this?
$( "#target" ).keyup(function() {
alert( "Handler for .keyup() called." );
});
You need to use .prop() to add/remove disabled attribute of button. The function get true/false in second parameter that add/remove target attribute.
$( "#target" ).keyup(function() {
$("button").prop("disabled", !this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="target" />
<button disabled>Next</button>
See result of code demo on your code
I like to use .on() with jQuery, like so:
$("#InputFName").on("keyup", function() {
$("#BtnNext").prop("disabled", false);
if( $("#InputFName").val() == '') {
$("#BtnNext").prop("disabled", true);
}
});
If you want to disable your button :
$('#MyButton').prop('disabled', true);
And if you want to enable it again :
$('#MyButton').prop('disabled', false);
Replace #MyButton by what you need :
$('#id') to get the element by ID
$('.class') to get the element by class
$('tag') to get the element by tag name
Yes, you could also do the check on the blur event of the input
$( "#target" ).blur(function() {
//check if your need to disable the button
});
Keep in mind that is really easy to bypass the disabled state of the button.
Yes, you can use the keyup event, and even better would be the input event, since it catches pasting and other types of inputs.
Inside that event handler, you can just check the inputs value, and make a condition that returns a boolean, that can then be used to set the disabled property of a button
$( "#target" ).on('input', function() {
var val = this.value;
$('#button').prop('disabled', val === "some value")
});
And it will update as the user types
In your case, it looks like you want to check three inputs, and if they all have a value, you enable the button, and you'd do that like this
var elems = $('#InputFName, #InputLName, #InputAge').on('input', function() {
var bool = elems.filter(function() {
return this.value.trim() !== "";
}).length !== elems.length;
$('#BtnNext').prop('disabled', bool);
});
$(document).ready(function() {
// Hide the inputs
$("#InputFName").hide();
$("#InputLName").hide();
$("#InputAge").hide();
$("#BtnNext").prop("disabled", true);
// When the user clicks the First name button
$("#BtnFName").click(function() {
$("#InputFName").show();
$("#InputLName").hide();
$("#InputAge").hide();
});
// When the user clicks the Last name button
$("#BtnLName").click(function() {
$("#InputFName").hide();
$("#InputLName").show();
$("#InputAge").hide();
});
// When the user clicks the Age button
$("#BtnAge").click(function() {
$("#InputFName").hide();
$("#InputLName").hide();
$("#InputAge").show();
});
var elems = $('#InputFName, #InputLName, #InputAge').on('input', function() {
var bool = elems.filter(function() {
return this.value.trim() !== "";
}).length !== elems.length;
$('#BtnNext').prop('disabled', bool);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Container">
<h3>User Form</h3>
<p>Fill out details:</p>
<button id="BtnFName" class="SrcButton">First name</button>
<button id="BtnLName" class="SrcButton">Last name</button>
<button id="BtnAge" class="SrcButton">Age</button>
<br />
<!-- Input Container -->
<input id="InputFName" placeholder="First Name" />
<input id="InputLName" placeholder="Second Name" />
<input id="InputAge" placeholder="Age" />
<!-- Next Button Container -->
<br />
<button id="BtnNext" class="BtnNext">Next</button>
</div>
$('#InputFName').keyup(function() {
if ($("#InputFName").val() != null) {
$("#BtnNext").removeAttr('disabled');
}
if ($("#InputFName").val() == '') {
$("#BtnNext").attr('disabled', true);
}
});

Disable a particular span using jQuery

I am creating a calendar event app where you can save people's birthday dates and edit people's names or dates whenever you want.
To display stored events I am using a forEach loop in JSP. I have a span named ld-option-okay-edit in each div. You can edit previous data after you click on that span and save your data.
But before clicking on the save button I am checking whether any field in a particular div is empty or not, using a jQuery hover function.
If any field is empty then I am disabling the span element so that it can't forward request to the servlet, but the problem is I am not able to disable it.
??????
THE PROBLEM
???????
My question is how can I disable a span through jQuery, or how can I prevent the onclick event of a span using jQuery?
Here is my code:
<c:forEach items="${relativeUser}" var="user">
<div class="elementsdiv">
<form action="<c:url value=" ******">" method="post">
<div class="cld-option-okay" >
<span class="glyphicon glyphicon-ok cld-option-okay-edit" name="cld-option-okay-edit" ></span>
</div>
<div class="cld-option-name" >
<input class="cld-name-input" value="${user.name}" placeholder="Name of the person" type="text" name="name">
</div>
</form>
</div>
</c:forEach>
What I have tried until now in jQuery is:
$(".elementsdiv").each(function (i, data) {
$($(data).find('.cld-option-okay')).hover(function (e) {
e.preventDefault();
if ($($(data).find('input[name="name"]')).val() === "") {
$($(data).find('span[name="cld-option-okay-edit"]')).addClass('disabled');//in this line i am getting trouble
}
}
});
For that line I even tried:
1)$($(data).find('span[name="cld-option-okay-edit"]')).attr("disabled","true");//with single quote also
2)$($(data).find('span[name="cld-option-okay-edit"]')).attr("disabled","disabled");//with single quote also
3).prop("disabled", true );
4).attr('disabled', '');
5).attr("disabled", "disabled");
6).off( "click", "**" );
7).unbind( "click", handler );
but when I apply:
`$($(data).find('span[name="cld-option-okay-edit"]')).hide()`;//it is applying
**********************
`$($(data).find('span[name="cld-option-okay-edit"]'))`till here code is working fine my problem is in applying disable.
previously i applied disable like below
$('.cld-option-okay-edit').addClass('disabled');
but it disables okay span in all divs
*************************
For enable or disable a span, you could do it like this:
var isEmpty = false;
$('#myDiv > input').keyup(function(){
isEmpty = false;
$('#myDiv > input').each(function(i,obj){
if(this.value == ""){
isEmpty = true;
return false;
}
});
// Styles for the span.
if( ! isEmpty){
$('#myDiv > span').removeClass('disabled');
} else {
$('#myDiv > span').addClass('disabled');
}
});
$('#myDiv > span').click(function(){
if(isEmpty){
alert("disabled");
} else {
alert("enabled");
}
});
I think this is what your code should look like based on what you have written, but I am not sure it is actually what you want to happen. If you want to disable it, you need to use prop()
$(".elementsdiv").each(function() {
var elem = $(this);
elem.find('.cld-option-okay').hover(function(e) {
if (elem.find('input[name="name"]').val() === "") {
elem.find('span[name="cld-option-okay-edit"]').addClass('disabled'); /*.prop("disabled",true); */
}
});
});

avoid "submit" when user hits enter in form with only one input

I'm using (all right, just starting to learn) bootstrap and javascript and jQuery. I have a rather extensive experience in other programming languages, and I like understanding what happens.
so I have a dialog box containing just one input box, and I do not want a POST action to be fired when the user hits enter. I am using a dirty trick according to me, and I'm wondering how to do this more neatly.
<div class="modal-body">
<form enctype="multipart/form-data" class="well">
<input id="empty" name="empty" type="hidden"/></form>
<table width="100%">
<tr><td width="30%">accession#.plant#</td>
<td><input id="addendum" name="keyword" type="text"/></td></tr>
</table>
</div>
the unused "empty" form, it's the dirty trick that works for me on firefox 27.0.1
I have tried disabling the enter key completely, as suggested by answers to similar questions, but it has a non desirable side effect according to me: when entering data in a input element, the browser will give hints. disabling the enter key makes difficult selecting among them.
It's hard to tell without seeing the JavaScript, but you should be able to call preventDefault on the event object in JavaScript. This keeps the form from submitting, but shouldn't interfere with the type ahead behavior in browsers.
Give the form an id and then put the id in the keypress function... It should work.
<script type="text/javascript">
$(document).ready( function() {
$('#[formid]').keypress(function (e) {
if (e.which == 13) {
e.preventdefault();
return false;
}
});
});
</script>
You can use this, it will prevent form submission if no field have been inputed.
$( ".well" ).on( "submit", function() {
var has_empty = false;
$(this).find( 'input' ).each(function () {
if ( ! $(this).val() ) { has_empty = true; return false; }
});
if ( has_empty ) { return false; }
});
EDIT: Biding it to the enter listener:
$(".well").bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
var has_empty = false;
$(this).find( 'input' ).each(function () {
if ( ! $(this).val() ) { has_empty = true; return false; }
});
if ( has_empty ) { return false; }
}
});

Disable opposite input if I type into another of a pair

How do I disable one input field if I type into another out of a pair and then if I removed the input by hitting backspace for example so there is nothing in the input field reenable the second input field and vice versa. Code I have so far is below but is not working.
JavaScript:
//disable the opposite input field
var ATGvalue = $('input#atgOrderId').val();
var BQvalue = $('input#bqOrderId').val();
if ( ATGvalue.length > 0) {
$('input#bqOrderId').prop("disabled", true);
} else {
$('input#bqOrderId').removeAttr("disabled");
}
if ( BQvalue.length > 0) {
$('input#atgOrderId').prop("disabled", true);
} else {
$('input#atgOrderId').removeAttr("disabled");
}
HTML:
<label for="bqOrderId">bqOrderId </label><input name="bqOrderId" id="bqOrderId" type="text" />
<label for="atgOrderId">atgOrderId </label><input name="atgOrderId" id="atgOrderId" type="text" />
Your code does work, but only once - to have it continuously update, you first wrap the JS in an event-handler function and attach it to your input elements:
function mutuallyExclusive( e ) { ... }
$( '#bqOrderId' ).on( 'change keyup', mutuallyExclusive );
$( '#atgOrderId' ).on( 'change keyup', mutuallyExclusive );
See this JSFiddle.
I attached it to both the change and keyup events: change to handle programatic (scripted) changes, and keyup to "instantly" update the fields' statuses - otherwise it waits till the user removes focus from the input to call the change event.
you need to include your code inside an event to check when a user type something like this:
$(document).on('keyup','#bqOrderId',function(){
//your code
});
$(document).on('keyup','#atgOrderId',function(){
//your code
});
after to change this:
$('input#bqOrderId').prop("disabled", true);
$('input#atgOrderId').prop("disabled", true);
to this:
$('input#bqOrderId').attr("disabled",true);
$('input#atgOrderId').attr("disabled", true);

Stop reloading page with 'Enter Key'

I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the apropriate JavaScript takes place without reloading the page. The problem is that the page keeps reloading. Here is my latest attempt:
$("searchText").bind('keyup', function(event){
if(event.keyCode == 13){
event.preventDefault();
$("#buttonSrch").click();
return false;
}
});
<input type='search' id='searchText' />
<input type='button' id='buttonSrch' onclick="search(document.getElementById('searchText'))" value='Search' />
Don't bind to the inputs; bind to the form. Assuming the form has an ID of searchForm:
$("#searchForm").submit(function() {
search($("#searchText").get(0));
return false;
});
Try it out.
It can also be done with plain JavaScript:
document.getElementById('searchForm').addEventListener('submit', function(e) {
search(document.getElementById('searchText'));
e.preventDefault();
}, false);
I know its a little late but I ran into the same problem as you. It worked for me using "keypress" instead of bind.
$('#searchText').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
//do something
}
});
You are missing # in the selector. Try this
<input type='text' id='searchText' />
JS
$("#searchText").bind('keyup', function(event){
if(event.keyCode == 13){
event.preventDefault();
//$("#buttonSrch").click();
search(this.value);
}
});
Add onSubmit="return false;" on your form tag
<form onSubmit="return false;">
/* form elements here */
</form>`
$('#seachForm').submit(function(e){
e.preventDefault();
//do something
});
You could set the form action attribute to javascript:void(0); that way the form doesn't post/get so the page wont refresh.
$(document).ready(function () {
$('#form1').attr('action', 'javascript:void(0);');
});
Just use the "action" attribute in <form> tag.
Like this
<form action="#"> // your content </form>
$("searchText").keypress(function(event){
if(event.keyCode == 13){
$("#buttonSrch").click();
return false;
}
});
Does your JS execute immediately or on document ready? If it's not in a document ready the button won't exist at the time you're trying to call bind.
This is what ended up working for me. Please note that my struggle was to find the object that triggered the form submit:
$('#missingStaff').submit(function (e) {
e.preventDefault();
var comment = $(document.activeElement)[0];
submitComments(comment);
});
You just need to add this:
<form #submit.prevent="search">
whatever function is triggered for search. When I press that search button search() func is triggered. That is why: #submit.prevent="search"
async search() {
let yuyu = document.getElementById('search').value
console.log('lsd', yuyu)
try {
let newRecipes = await this.$axios.$get(
`/api/videosset/?user=&id=&title=${yuyu}&price=&category=`
)
this.$store.commit('CHANGE_NAV_LAYOUT', newRecipes)
} catch (e) {
console.log(e)
}
},

Categories

Resources