i have a text field on my page that has an autocomplete featuring items from a database. When selected this scrolls the page using jquery to where that result is on the page. I want the form to scroll to the result on submit button instead of having to click the text field again. How would i edit my code so that it happens on submit, rather than on text field click
form code -
<form autocomplete="off">
<form name="search-highlight" id="search-highlight" method="post" action="#">
<p>
Film Name <label>:</label>
<input type="text" name="scroll" id="scroll" class="scroll"/>
<!--input type="button" value="Get Value" /-->
</p>
<input type="submit" value="find" />
</form>
and the javascript
$("#scroll").autocomplete("get_film_list.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
$("#scroll").click(function(){
// start variables as empty
var scroll = "";
var n = "0";
// hide the results at first
$("p.results").hide().empty();
// grab the input value and store in variable
scroll = $('#scroll').attr('value');
console.log("The value of film is: "+scroll);
$('span.highlight').each(function(){
$(this).after($(this).html()).remove();
});
if($('#scroll').val() == ""){
$("p.results").fadeIn().append("Enter film in field above");
$('#scroll').fadeIn().addClass("error");
return false;
}else{
$('div.timeline :contains("'+scroll+'")').each(function(){
$(this).html($(this).html().replace(new RegExp(scroll,'g'), '<span class="highlight">'+scroll+'</span>'));
$(this).find('span.highlight').fadeIn("slow");
var offset = $(this).offset().top
$('html,body').animate({scrollTop: offset}, 2000);
return false;
});
// how many did it find?
n = $("span.highlight").length;
console.log("There is a total of: "+n);
if(n == 0){
$("p.results").fadeIn().append("No results were returned");
}else{
$("p.results").fadeIn().append("<strong>Returned:</strong> "+n+" result(s) for: <em><strong>"+scroll+"</strong></em>.");
}
return false;
}
});
});
I hope you understand my problem - if not heres a demo (not optimized) www.ignitethatdesign.com/CheckFilm/index.php
DIMENSION
If you change the $("#scroll").click( to target the submit button (something like $("#search-highlight input[type='submit'].click) should get you the behavior.
You should probably expand the signature of your click callback to include an event argument, as in
.click(function(event)){ so later on you can call event.stopPropagation(), to indicate to the browser the click event on your input has been handled (and it doesn't try to post the form back).
Related
I am trying to disable the function I pass to addEventListener when the user clicks on submit. I put code in to prevent user from leaving page if they have entered data on any of the fields. This works fine. If the user tries to navigate away they get a warning as expected. However, I can't seem to figure out how to disable this feature once all of the fields are populated and the user clicks submit. As it stands, they are prompted to make sure they want to navigate away when they click on submit and I don't want this to happen when the user clicks submit.
I've tried something like the below, to try to unbind the beforeunload function based on submit, but this isn't working. I feel like this is the right general idea, but I'm struggling to make this work as I want it to.
$('form').submit(function() {
$(window).unbind('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
The code below works as expected:
window.addEventListener('beforeunload', function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if (inputValue.length > 0) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
If the user clicks submit I want the beforeunload function to be turned off essentially.
Was able to solve this problem using the suggestion that was made by Bipperty via this SO issue...Narrow Down BeforeUnload To Only Fire If Field Is Changed or Updated. Ultimately the code below is what I used to turn off beforeunload when submitting the form....
var submitting = false;
window.addEventListener("beforeunload", function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if(inputValue.length > 0 && submitting === false) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
document.addEventListener("submit", function(event) {
submitting = true;
});
If you bind a handler using .on() you can remove the bound event using .off()
$('form').submit(function() {
$(window).off('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
However, I feel in your scenario you don't really need the beforeunload at all if you handle your form submit logically.
I've mocked up an example of how you can logically submit the form if a user chooses to submit the form based on a condition (in this case if all fields aren't filled).
$('form').on('submit', function (e) {
var inputs = $(':text', this);
console.log(inputs.length)
var validInputs = inputs.filter(function () {
return $(this).val().length;
}).length;
if (validInputs > 0 && validInputs < inputs.length) {
var r = confirm("Are you sure you want to leave?");
if (!r) e.preventDefault()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://google.com" method="get">
<input name="a" placeholder="Input 1">
<input name="b" placeholder="Input 2">
<input name="c" placeholder="Input 3">
<button type="submit">Submit</button>
</form>
Update
To prompt the user before leaving a form:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
See this post
Use the required attribute on each field and you won't need to do all of that. The following demo will refuse any attempts to submit it's form if there's a blank field. It will send to a live test server and a response will be displayed verifying a successful submission.
Demo
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
label {
display: inline-block;
width: 75px
}
[type=submit] {
margin-left: 200px
}
<form id='form' action='http://httpbin.org/post' method='post' target='response'>
<label>Name: </label><input name='Name' type='text' required><br>
<label>Cell: </label><input name='Cell' type='tel' required><br>
<label>Date: </label><input name='Date' type='date' required><br>
<input type="submit">
</form>
<iframe src='about:blank' name='response'></iframe>
First, thanks for taking the time to look at my question. Really. This is my question. I'm making a fancybox search page for a website I'm making. Getting the search results in fancybox all work fine.
But if the visitor just clicks on search it returns every item on the site. What I would like is make the form so, that the visitor has to at least enter 3 characters before the search does a search. If the visitor doesn't enter 3 or more characters fancybox will give an alert saying please enter at least 3 or more characters.
I've looked around stackoverflow and found this code:
$( document ).ready(function() {
input_value = $.trim($('#searchkey').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
}else{
//perform your code if it should not be empty.
}
});
So I placed my code inside the correct place, like so:
$( document ).ready(function() {
input_value = $.trim($('#str').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
} else {
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
jQuery.fancybox({
width: 600,
height: 600,
openEffect: 'fade',
closeEffect: 'fade',
href: 'search-post-results.php',
type: "ajax",
ajax: {
type: "POST",
data: {
value: $('#str').val()
}
}
});
});
});
}
});
I'm not getting any syntax errors, but if I reload the page it gives me the correct alert. But thats if there are no characters entered. So I've changed this line:
if(input_value == ''){
to:
if(input_value == '2'){
Figuring that I should set a value. But that does nothing. Does anyone have a similar script/snippet that does the same? Or know why this isn't working?
Here is the HTML (nothing special there):
<form id="search">
<table>
<tr>
<td>
<input type="text" name="s" id="str" placeholder="Search...">
</td>
<td>
<button class="btn form-button btn-default">
<i class="fa fa-search"></i>
</button>
</td>
</tr>
</table>
</form>
Thans again for your time.
Use length property.
if( input_value.length < 3 ){
// error message if characters are less than 3
} else {
// continue the search
}
Try this ,
Also Please change validation position because if you reload then always alert will show . So you can validate after submit action.
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
if(input_value.length < 3 ){
// Show your alert message.
}else{
// Here you start Ajax Request.
}
});
});
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 this form when information is being store into DB. I have a checkbox and a text field. Either one are required, but if the text field isn't empty, there's a good chance the checkbox should be checked. So I'd like to display an Alert if the Text Field has a value in it, and the checkbox isn't checked. I'd like this alert to appear when hitting the Submit button. Here's my form:
<form id="form" name="form" action=?post=yes" method "post">
<input type="checkbox" name="close" id="close" value="Yes"><label for="close" title="Close this RMA">Close this RMA</label>
<label><input type="text" name="dateshipped" id="dateshipped"/></label>
<button type="submit">Save and Continue</button>
</form>
So if checkbox "close" IS NOT checked AND "dateshipped" IS NOT NULL, then display alert when click Submit.
Thank you.
you can do a javascript function to be called on the onclick event in the submit button , like this
<button type="submit" onclick="callAfunction();">Save and Continue</button>
and define the function
callAfunction()
{
//do the checks with: document.getElementById('close').value
// display an alert("a message");
}
Would something like this work?
onsubmit="return validate();" // add to your form tag
function validate() {
checkbox = document.getElementById('myCheckbox').value;
if (!checkbox) {
alert('checkbox is empty');
return false;
} else {
return true;
}
}
Something like this perhaps?
Button for submitting. It runs validateSubmit. It only submits if the function is true.
<input type="button" value="submit" onsubmit="return validateSubmit();" />
Here's the validate function. It gets the value of the checkbox and the text. If they're both falsy then it sets valid to a confirm box. The confirm box allows the user to select ok or cancel and returns true or false based on that.
function validate() {
var valid = true;
var checkbox = document.getElementById('checkboxID').value;
var text = document.getElementById('textBox').value;
if(!(checkbox || text))
valid = confirm("Checkbox and text are empty. \n Continue?");
return valid;
}
The condition could be written as (!checkbox && !text), however I find it simpler to read to only use one ! if I can. The rule is called De Morgan's law if you're interested.
If you're using jQuery, things become easier.
var checkbox = $('#checkboxID').prop( "checked" );
var text =$('#textBox').val();
Plus you can attach even handlers like this:
$(document).ready(function() {
$('#btnSubmit').on('click', validate);
});
Let me know if you have any questions.
** Following code working for me, At first you need to add a onclick="functionName();" then do the following code**
function myCkFunction() {
var checkBox = document.getElementById("close");
if (checkBox.checked == true){
alert('checked');
} else {
alert('Unchecked');
}
}
I have text box called "userInput" and one submit button.I want to print the value of the text box which is entered by user like a stack(previous values also,not just the current value).
any idea..??
<input type="text" name="userInput"/>
<input type="button" name="sub" value="submit">
Thank in advance!
var stack = [];
$("input [name=userInput]").change(function () { stack.push(this.value); });
You can change that event to blur, focus, etc. depending on when you want the values recorded.
A submit button usually is for submitting a form. Submitting a form is sending a request to the server and refreshing the page. So in your server side script you could read the posted values and show them in the resulting page (you don't need javascript for this).
If you don't want to redirect you could handle the submit event and cancel the default submission:
var values = [];
$(function() {
$('#id_of_form').submit(function() {
// get the entered value:
var userInput = $(':input[name=userInput]').val();
// add the current value to the list
values.push(userInput);
// show the values
alert(values.join(", "));
// cancel the default submission
return false;
});
});
Tested solution:
<html>
<head>
<script type="text/javascript">
function AddToStack() {
var userInput = document.getElementById('userInput');
var stack = document.getElementById('stack');
stack.innerHTML += '<p>' + userInput.value + '</p>';
//clear input an refocus:
userInput.value = '';
userInput.focus();
}
</script>
</head>
<body>
<div id="stack"></div>
<input type="text" name="userInput" id="userInput"/>
<button type="button" name="sub" onclick="AddToStack();">Submit</button>
</body>
</html>