I have a navabar that uses anchors instead of links. I am making a chat feature and every time the user enters something into the chat, followed by enter, they are redirected to the first anchor. I know I need to probably use AJAX but I can't seem to figure it out. Here is the code.
<div id="tab3">
<h2>Chat Room</h2>
<div id="chatboxlog">
<div id="chatlog">
Loading chat please wait...
</div>
</div>
<div id="chatinput">
<form name="chatbox" class="userchat">
<input class="userchat" name="message" type="text" onkeydown="if (event.keyCode == 13) document.getElementById('chatbutton').click()"/><br>
<input class="userchat" id="chatbutton" name="submitmsg" type="button" onclick="submitChat()" value="Send" />
</form>
</div>
</div>
<script>
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
</script>
It seems to me you simply have an issue with your form being submitted (typically happens when user hits "Enter" while focus is on a form child element, other than a textarea) and it automatically reloads your page.
This happens for example when no action is specified on your form: the latter tries reloading what is currently in the browser navigation bar ("location"). In your case, if the location has a fragment (hash) to another anchor, the page will simply scroll to that anchor.
You can prevent the form submit action by using event.preventDefault(), either in your text input, or better on the form itself, by attaching a callback on the submit event.
// NOTE: try using id's rather than names.
// Select the appropriate form.
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
// Prevent the form from reloading the page.
event.preventDefault();
});
Demo: http://jsfiddle.net/8odryt5p/1/
Use preventDefault() to prevent form or page from reloading.
See Examples below
Click on Specific ID
$('#myId').click(function(e){
event.preventDefault();
});
For click on any class
$('.myClass').click(function(e){
event.preventDefault();
});
For click on Any Anchor inside page
$('a').click(function(e){
event.preventDefault();
});
To Prevent Page reload after click on any anchor inside a div or section
$('.myClass a').click(function(e){
event.preventDefault();
});
Related
This is what I want
Jquery:
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
alert();
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
Why I am doing this
Upper class is different for all buttons
But loader class is same for all buttons it shows loader inside clicked button
I found
e.stopPopagation();
But that works if I use it in loader click callback But I want to stop when button is clicked and url is empty
Cannot check url=="" inside loader click call back cause it is same for all button i dont want to check on other buttons click too so checking for single button
I would recommend using classes to check for condition.
$("body").on('click','.js-loader',function(){
var _this = $(this)
if(_this.hasClass('js-loader') && _this.hasClass('js-validate-url')){
// if both classes js-loader, js-validate-url are present on button
alert()
}else{
alert("js-loader") // if only js-loader present on button
}
});
I'm not sure if I understand what you are trying to do, but I guess you can merge your events into a single one and use an external function only when it met a condition.
You could also use removeEventListener but I don't believe you need it for your problem.
var myFunction = function(){
alert('loader');
};
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if (url){ alert('validate: '+url); }
else myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="google.com" class="url"/>
<button class="js-validate-url js-loader">Bt1</button>
<button class="js-loader">Bt2</button>
This is what I did and is working fine as per my requirement
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
$(this).removeClass("js-diable");
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-scud-disabled')){
//NOTHING TO DO
}else{
alert();
}
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url js-disable"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-loader js-validate-url')){
alert();
} else {
if(url==""){
} else {
}
}
});
I have a form which has a textarea:
<form id="hello">
<textarea id="Testarea" required></textarea>
</form>
<button id="myButton" type="submit" value="Submit">Click me!
</button>
When the user submits the form, I listen to it via a jquery handler:
$("#myButton").click(function () {
alert("blah");
});
However if the textarea is empty, I want an error to be thrown without calling my function. Right now, my function is called even if the textarea is empty.
https://jsfiddle.net/8dtsfqp0/
Use a submit handler on the form, not a click handler on the button.
Here is the order of execution when you click on a submit button:
Button's click handler is called. If it calls event.preventDefault(), the process stops.
The form is submitted, which performs the following steps:
Validate input fields. If any validation fails, the process stops.
Call the form's submit handler. If it calls event.preventDefault(), the process stops.
The form data is sent to the server.
So if you want to prevent your function from being called, it has to be after the "Validate input fields" step. So change your code to:
$("#hello").submit(function () {
//Throw error if textarea is empty
alert("Her");
});
Fiddle
you can try this:
$("#myButton").click(function () {
if($('#Testarea').val().trim().length > 0)
{
return true;
}
else
{
alert("empty text box");
return false;
}
});
<script type="text/javascript">
document.getElementById("myButton").addEventListener("click", myFunction);
var problem_desc = document.getElementById("Testarea");
function myFunction() {
if (problem_desc.value == '') {
alert("blank");
return false;
}
else{
alert("working");
}
}
</script>
I am using jQuery tabs and validating all fields are filled in prior to allow the user to move to the next tab. On a few of the tabs there are options where the user can choose from multiple options and, sometimes, the user will click option 1 and mean option 2 but when they try and click the previous button this validates the fields and won't let them until they have filled in all the fields which is a rubbish UX.
I would like to only validate on clicking a next button but not on clicking a previous button.
<a class="btn nexttab navbutton" href="#step1">Previous</a>
<a class="btn nexttab navbutton" href="#step3">Next</a>
Here is the code I am using currently:
var validator = $("#start").validate();
var tabs = $("#tabs").tabs({
select: function(event, ui) {
var valid = true;
var current = $(this).tabs("option", "selected");
var panelId = $("#tabs ul a").eq(current).attr("href");
$(panelId).find(":input").each(function() {
console.log(valid);
if (!validator.element(this) && valid) {
valid = false;
}
});
return valid;
}
});
To try and overcome this I added a class called next button to the next buttons only and then tried to change this line which I assume checks any input:
$(panelId).find(":input").each(function() {
to:
$(".nextbutton").click(function() {
but it allows the user to move to the next screen without having to fill in all the fields.
How can I make it so only forward movement is validated?
http://jsfiddle.net/553xmzh3/1/
I would like to only validate on clicking a next button but not on clicking a previous button. .... How can I make it so only forward movement is validated?
Simply put a cancel class on your "previous" button. All validation rules will automatically be ignored when a submit button contains a cancel class. However, the submitHandler will fire as if the form is valid.
<input type="submit" value="PREVIOUS" class="cancel" /><!--// This submit will not trigger validation //-->
<input type="submit" value="NEXT" /><!--// This submit will trigger validation //-->
Working DEMO: http://jsfiddle.net/4zdL8ha3/
EDIT:
Although it still works, using class="cancel" has been officially deprecated and replaced with formnovalidate="formnovalidate"
<input type="submit" value="PREVIOUS" formnovalidate="formnovalidate" />
Working DEMO: http://jsfiddle.net/4zdL8ha3/1/
Since you're using anchor tags instead of type="submit" elements, this solution will not work for you. It would be best to replace your anchor tags with a button element. That way, using CSS, you can style the button to look exactly the same as an anchor.
<button type="submit" class="btn nexttab navbutton" formnovalidate="formnovalidate">Previous</button>
<button type="submit" class="btn nexttab navbutton">Next</button>
Working DEMO: http://jsfiddle.net/4zdL8ha3/2/
EDIT:
If you must have anchor tags in place of type="submit" buttons, then you need to write the appropriate click handlers and check the form's validity only on the "next" button handlers. Using the .valid() method also simplifies your code by removing your custom validation tester from the tab switcher function.
$(".nexttab").click(function () { // NEXT BUTTON
if ($("#start").valid()) { // TEST VALIDATION
$("#tabs").tabs("select", this.hash);
}
});
$(".cancel").click(function () { // PREVIOUS BUTTON - NO VALIDATION TEST
$("#tabs").tabs("select", this.hash);
});
Initializations:
var validator = $("#start").validate();
var tabs = $("#tabs").tabs({
select: function (event, ui) {
var current = $(this).tabs("option", "selected");
var panelId = $("#tabs ul a").eq(current).attr("href");
return true;
}
});
DEMO: http://jsfiddle.net/553xmzh3/3/
I got this question regarding the forms target and its target window.. lets say we have this Html.BeginForm
#using (Html.BeginForm("TestHtmlRedirect", "Home", FormMethod.Post, new {#target="_blank", #id = "tagging_frm", #class = "form-horizontal row-border" }))
{
<input type="submit" value="Html PsBk Click" />
}
normally upon clicking the submit button it will trigger a new tab, my question is
How, or is it Possible to append something to the newly created tab of this form?
for example i want to append a loading gif on that newly created tab by the parent tab.
Assuming the actions and scripts are all from the same server/origin, you can do this:
$(function() {
$("#tagging_frm").on("submit",function(e) {
e.preventDefault(); // cancel submit
var w=window.open("",this.target);
w.document.write('<div id="container"><img src="loading.gif"/></div>');
w.document.close();
$.post(this.action,function(data) {
w.document.getElementById("container").innerHTML=data;
});
});
});
To load a csv or pdf try this alternative
$(function() {
$("#tagging_frm").on("submit",function(e) {
e.preventDefault(); // cancel submit
var w=window.open("",this.target);
w.document.write('<form id="myForm" action="'+this.action+'" target="myframe" method="post"></form><img id="loading" src="loading.gif"/><iframe name="myframe" onload="document.getElementById(\'loading\').style.display=\'none\'"></iframe>');
w.document.close();
w.document.getElementById("myForm").submit();
});
});
What I am trying to do is following:
I have an input type button and I want to replace it's function on first click.
<input type="submit" class="submit-button" value="Submit" name="boom" />
So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).
So on first click it will be
alert('Something');
And on second click it will be default function (submit).
How can I achieve something like this?
Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.
Use one().
Attach a handler to an event for the elements. The handler is executed at most once per element.
Example:
$(".submit-button").one("click", function(e) {
// will only run on first click of element
e.preventDefault();
alert("Something");
});
Try this:
<script type="text/javascript">
var clicked = false;
function btnClick(e) {
if(clicked === false) {
alert('Something');
clicked = true;
e.preventDefault();
return true;
} else {
return false;
}
}
</script>
<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />