Blur() event doesn't work for me - events

This is my jQuery code:
$('input[name="Search"]').blur(function(e) {
$(this).text('');
});
And my HTML snippet:
<input name="Search" type="text" id="Search" class="MainMenu" />
But it doesn't work, does anybody know why?

try .val() insteadof .text()
$('input[name="Search"]').blur(function(e) {
$(this).val('');
});​

You are using text() on input type text which is not defined for input type=text. You need to use val()
Live Demo
$('input[name="Search"]').blur(function(e) {
$(this).val('');
});​
If you have id, you can use id as it will be more efficient then getting element with name selector.
Live Demo
$('#Search').blur(function(e) {
$(this).val('');
});​

there is no method like .text() for input type text use .val()
these change will help you
$('input[name="Search"]').blur(function(e) {
$(this).val('');
});
or
$('#Search').blur(function(e) {
$(this).val('');
});​
Documentation here

Related

AJAX shows different behaviors in an if/elseif-statement which is inside the success function [duplicate]

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

CKEditor - get attribute of element with Onclick

I'm trying to get the value of the attribute data-time-start when I click on the span.
My FIDDLE : http://jsfiddle.net/zagloo/7hvrxw2c/20/
HTML :
<textarea id="editor1"> <span class="sub" id="sub1" data-time-start="0">Hello </span>
<span class="sub" id="sub2" data-time-start="2">My </span>
<span class="sub" id="sub3" data-time-start="6">Name </span>
<span class="sub" id="sub4" data-time-start="8">Is </span>
<span class="sub" id="sub5" data-time-start="12">Zoob</span>
</textarea>
My JS:
var textarea;
$(document).ready(function () {
textarea = $('#ckeditor_block').find('textarea').attr('id');
ckeditor_init();
});
function ckeditor_init() {
CKEDITOR.replace(textarea, {
language: 'fr',
allowedContent: true
});
}
I tried with this:
CKEDITOR.on('click', function (e) {
var element = $(e.target);
console.log(element);
var cursor = element.data("timeStart");
console.log(cursor);
});
But nothing appened ...
How to do that please ? thank you !!
You can't (or better you shouldn't) use the default jQuery event/element handling in this case, because the CKEditor comes with its very own event/ element system.
Update: Based on the comments below, to avoid CKEditor's quirky behaviour, it is better to use attachListener instead of jQuery's 'on' to bind an event listener
Step one: Bind the click event:
var editorInstance = CKEDITOR.instances['editor1'];
editorInstance.on('contentDom', function() {
editorInstance.editable().attachListener(
this.document,
'click',
function( event ) {
// execute the code here
}
);
});
Step two: Find and access the data attribute:
var editorInstance = CKEDITOR.instances['editor1'];
editorInstance.on('contentDom', function() {
editorInstance.editable().attachListener(
this.document,
'click',
function( event ) {
/* event is an object containing a property data
of type CKEDITOR.dom.event, this object has a
method to receive the DOM target, which finally has
a data method like the jQuery data method */
event.data.getTarget().data('time-start');
}
);
});
For more info check the CKEditor docs.
Updated fiddle is here

javascript not working form.textid.indexOf("")

I have this code and it worked for a few minutes. However I reloaded my page and now I cannot get it to work and I cannot figure out why. Any help would be much appreciated.
Code:
<form>
<input type="text" id="test">
<input type="button" value="test" onclick="check(this.form)">
<script lang="JavaScript">
function check(form) {
if (form.test.indexOf("yes")) {
alert("play sound");
}
else {
alert("no sound");
}
}
</script>
</form>
When I tested your code in Google Chrome's Javascript console, I got Typeerror: cannot read property 'test' of undefined. It looks like you're trying to validate the user input in the input box, but whatever value entered needs to be referenced in your code before finding the string segment of that string with the indexOf ().
Here's a jsFiddle of showing you how to get the user input value with jQuery.
Use jQuery's val() method or Javascript's value() method to get the user input, then you can use indexOf method to find the string segments
var arr=["random","Javascript","donuts","closures"];
$(document).ready(function() {
$("#myForm").submit(function(e){
e.preventDefault();
var userInput=$("#userInput").val();
if($.inArray(userInput,arr) != -1){
alert("success");
}
})
});

Javascripts don't work after calling changePage()

Javascript doesn't work after calling changePage() in my example. Everything is fine after first request page, but when I try to select other items, changePage() doesn't work. 'pageshow' event didn't help me. What's wrong with me?
My simple example:
#model TestMobileSearch.Models.ListModelView
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
$(document).delegate("#main", "pageinit", function () {
$("#filterCategory").bind('change', function () {
$.mobile.changePage(this.value);
});
});
</script>
Category Name: #Model.CurrentName
<select id="filterCategory" data-theme="c" data-corners="false">
#foreach (var item in Model.Names)
{
<option value="#Url.Action("List", "Cat", new {name = item})">#item</option>
}
</select>
I use jquery.mobile-1.3.1.js
Thanks
Why don't you delegate directly the #filtercategory change event?
$(document).delegate("#filterCategory", "change", function () {
$.mobile.changePage(this.value);
});
By the way, delegate is deprecated. If you use a newer jQuery, use on instead.

Conditional validation in MVC3

In MVC3, there are a way to add or stop validation in a field depending on the value of a drop-drown list with JQuery? I have been trying with Fluent Validation, but with no luck.
Are you using unobtrusive validation? Is so, look at the html and you will see that there are some html5 attributes on your input, something like this:
<input name="product" id="product" data-val="true" data-val-required="Product is required" />
I suppose you could use jQuery to remove the data-val attribute and then the jQuery Validator will skip this item.
$("#product").data("val", false);
Well, that's my guess, try it yourself.
you should use jQuery AddClass Rules
Create jQuery Class
$.validator.addClassRules({
Req: {
required: true
}
});
Validate the Filed by checking the selected value
$("#Selector").blur(function () {
var Val= $("#Selector").val();
if (Val == "Compare to the String") {
$("#Selector").addClass("Req");
}
else {
$("#Selector").removeClass("Req");
}
});

Resources