I have a text box in index.jsp and after writing something i am calling a jsp by jquery. But my requirement is if a particular value will be matched in server side then how can i auto refresh that text box? It means suppose i entered apple then by onkeyup event i am sending the name(apple) to check.jsp and in this jsp page, I have kept apple in a string. So now an alert will come in index.jsp that apple already exists and simulatenously that text box will be auto refreshed. How can i do it? I am a beginner to this field.
index.jsp
<script type="text/javascript">
$(document).ready(function() {
$("#textbox").keyup(function () {
$.getJSON('check.jsp', {
textboxname: this.value
});
});
});
</script>
inside body
<input type="text" id="textbox" name="textboxname"/>
check.jsp
String textboxname=request.getParameter("textboxname");
on keyup send the value to the server and if it matches return true or false, then in the success handler check what is returned if its true refresh and not do something
$("#textbox").keyup(function () {
$.getJSON('check.jsp', {
textboxname: this.value
},function(data){
if(data.isTrue){
alert("the value already exists");
$("#textbox").val(''); //clear the text box
}
else
//do something
});
});
});
on the server not the exact servlet code but you'll get the idea
JSONObject match = new JSONObject();
//if value matches
match.put("isTrue","true");
else
match.put("isTrue","false");
response.setContentType("application/json");
response.getWriter().write(match.toString());true
Related
I am using AJAX live search plugin.
It passes input data to backend-search.php
backend-search.php selects data from the database and return to the search page.
Now I want to pass one hidden input value with the search query.
Hidden Input
<input type="hidden" name="group" value="<?php echo $grp_id; ?>" />
Following is my html in search.php
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search..." />
<div class="result"></div>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
How do I send the data of the hidden input field with above js?
You could use $.post instead of $.get like this:
$.post( "backend-search.php?query="+ term, { hidden_key: "hidden_value"})
.done(function(data) {
alert( "Data Loaded: " + data );
});
So, customizing it for your code,
if(term.length) {
// get value of hidden field
var hidden_value = $('[name="group"]').value();
// make a post request, but also pass query params
$.post("backend-search.php?query=" + term, { group: hidden_value})
.done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
Here, everything after the ? mark is passed as a query string (i.e. via get method) whereas the hidden field is passed by the Post method.
In your Php script, use print_r($_REQUEST) to verify that you get the 2 parameters as desired.
Also, you should encode URI parameters like this encodeURIComponent(term) to make sure your javascript does not break if the user enters special characters
If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-
I have a textbox and button. I want to show an alert when I click the button. But I have a condition; the innput text value must be X1. If user write X1 in to textbox, show an alert GOOD otherwise alert NOT GOOD.
How can I do that with using jQuery? Here are my html codes.
<input type="text" id="couponInput" class="couponInput" placeholder="Input Code" />
<button type="button" id="couponApply" class="couponApply">APPLY</button>
In case you want specific jquery answer. Here it is ....
$(document).ready(function(){ // Document ready event -- most important
$('#couponApply').click(function(event){
var couponInputval = $('#couponInput').val(); // Getting the input value
couponInputval = couponInputval.toUpperCase(); // Changing to upper case
if(couponInputval == 'X1') {
alert("GOOD");
}
else{
alert("NOT GOOD");
}
event.preventDefault(); // To restrict button to push request to the server
});
});
Hope it helps ......
Add this javascript
//This detect the onClick event on your button
$("#couponApply").click(function(){
//here you retrieve the value of your input
var inputValue = $("#couponInput").val();
//And now, you test it
if(inputValue == "X1")
alert("GOOD");
else
alert("NotGOOD");
});
You can test it here
You don't need jQuery for that, but try this
<button type="button" id="couponApply" class="couponApply" onclick="if($('#couponInput').val() == 'X1'){alert('GOOD');} else {alert('NOT GOOD');}">APPLY</button>
Also if you are trying to verify coupons than this is not a good way to do that - your code will be easy to read in source of your website - you should do it on the server side
I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)
I have a form that I need to do some validation on, my jquery seems to be working except when a user just enters the page and submits without making any entry into a text box. Here is my HTML:
...
<% while (rs.next()) { %>
<input type="text" name="name" />
<% } %>
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
....
and my script:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
fafsaNbr = parseInt($("input[name='fafsaNbrFam']").val());
if (fafsaNbr > numEntries && !confirm("WARNING, numbers don't match.")) {
e.preventDefault();
}
});
So basically if their number of text boxes filled with names isn't >= the hidden input value then the kick back happens, and it works except when the user never enters anything into the text box. What event could I use instead of
$("input[name^='name_']").each(function() {
to accomplish this?
According to me it wont work because when textbox is empty then
$("input[name^='name_']").each(function()
parseInt($("input[name='fafsaNbrFam']").val());
.each() and val() return null. Due to this your control did not run ahead.
One thing you can do:
document.getElementById("fafsaNbrFam")==null
using this you can check the value as true or false. Because in case of empty textbox when you write the document.getElementById("fafsaNbrFam") or $("#fafsaNbrFam") it return value null.
And, null.val() or null.each() gives error.