How can implement enter key action in a form - javascript

In my php application i am using textfield and button[search].
when i am entering some data and i press Enter key the button action is not working.
can some one help on this.
My code like,
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script>
function clearerrormessage()
{
document.getElementById('info').innerHTML="Enter a keyword to find prospective customer";
}
function submi()
{
/*$('#keyword').keyup(function(e) {
if (e.keyCode == 13) {
$('#form1').submit();
}
});*/
keyword1 =document.getElementById('keyword').value;
//var unvalidkey = new Array("is","am","a","b",'',"are","was","were");
var unvalidkey = new Array("is","am","a","b",'',"are","was","were","+","/","%",".","&","\\","\"","'","?","#");
for(keyitem in unvalidkey)
{
if(unvalidkey[keyitem]==keyword1)
var f=0;
}
if(f==0)
{
document.getElementById('info').innerHTML = '<h3><font color = red>Please enter a valid keyword to search</font></h3';
return false;
}
keyword=keyword1.replace(' ','_');
$.post( "<?php echo base_url() ?>ajax/followsearch.php", { keyword : keyword })
.done(function( data ) {
$("#content1").html("<div id ='content'></div>");
$('#content').scrollPagination(
{
nop : 30, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No Results To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
);
});
}
</script>
</head>
<body>
<form id="form1" name="form1" action="" />
<div id="followkeyword">
<input type="text" style="width:300px;height:26px" name="keyword" id="keyword" onClick="clearerrormessage()" />
<div id="info1"><span id="info">Enter a keyword to find prospective leads</span>
</div>
</div>
<div id="followperloc">
<input type="button" name="mysubmit" id="mysubmit" value="Display my prospective leads" onclick="return submi()"/>
</div>
</form>
</body>
</html>
this code properly working in button click. But i need to also work in enter key submission. Please anyone help me..

Check for event keycode 13 to detect enter key.Try this:
Html: Use onkeypress instead onclick because onclick is a mouseevent.
<input type="button" name="mysubmit" id="mysubmit" value="Display my prospective leads"
onkeypress="return submi(event)" onclick="return submi(event)"/>
javascript:
function submi(event) {
event.which = event.which || event.keyCode;
if(event.which == 13 || event.which == 1) {
// wrap up your entire code here
}
}

Related

Using ENTER key to replace button click?

<body>
<form>
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
I have a very simple HTML file with minimal javascript included. When I click the button, it works perfectly. But when I hit the ENTER on the keyboard to simulate the button click, it will also run through the code, but then an error happens at the end.
On Firefox and Chrome, it'll return an error "Not Found". On w3schools, it'll return "The file you asked for does not exist". And on stackoverflow, it'll just disappear.
What am I missing? Where is the error? What's the trick to making the ENTER key act just like the mouse click?
HTML form has onsubmit attribute on them. onsubmit handles the enter functionality. You have to set the type="submit" on the button, also you need to set the onsubmit on form passing the event to your function so that you can prevent the default action of the form ( that is to send the request to backend ) by doing e.preventDefault.
<body>
<form onsubmit="calc(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="submit">read</button>
</form>
<br>
<label id = "calculated"></label>
<script>
function calc(e) {
// Will stop the form from sending the request to backend
e.preventDefault()
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
If you want to just prevent ENTER from doing anything including running the code....
The following code (yours with a couple more lines... will prevent Enter from doing anything:
<body>
<form onsubmit="return mySubmitFunction(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
return false;
//document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function mySubmitFunction(e) {
e.preventDefault();
return false;
}
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
Why was this happening? since the form element itself has a submit and the enter key is a key pressed which also does a form submit.... so you need to prevent the form from submitting... mySubmitFunction() <- this prevents the form from submitting ... and a change to your keyup event listener - if you do not want enter to even create the click you change this:
event.preventDefault();
document.getElementById("btn").click();
to this :
event.preventDefault();
return false;
//document.getElementById("btn").click();
As I have already did in the code example. or leave it like you had(the event listener keyup) and the Enter key will only act as a click.

Automatic keypress on page load

I have an input area where a value has been preset. I would like to make it so that on page-load the "enter" button is pressed on the keyboard to submit the value.
Here is the code:
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
}
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
A solution where I would not need to press enter and the value is submitted is also welcome!
I guess code below would work.
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
console.log('triggered')
player_name = $(this).val();
logged = 1;
}
})
const event = new Event('keypress')
event.which = 13
document.querySelector('#login-input').dispatchEvent(event)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
The doc
If you want it to run after page loaded, use onload event. The solution may look like this:
<script>
function f() {
// Test it:
// alert("Hello, page loaded!");
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="f()">
If you do want user to have a glimpse on your pre-filled login form and inform about what is happening, you may make a delay with setTimeout function, which will fire in 0.5 sec after onload event happened.
<script>
function f() {
$('#some_element').text('Signing you in...');
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="setTimeout(f, 500)">
Or you can call the event handler with a faked keypress like this:
function kpress(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
console.log(player_name,logged);
}
}
kpress.call($('#login-input').keypress(kpress),{which:13});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
I use the output from the jQuery event binding as the object context for the Function.prototype.call() method and add a "simplified" event object as {which:13}.

Unable to get the value of the clicked button when two button elements shared the same name [duplicate]

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));

jQuery client side password verification

first of all I'd like to say I realise it's not a secure method.
This is only for training purpose.
The algorhitm should be:
click on a div with id="login-bg"
app displays the banner
provide the code
if the code's ok set cookie and fade out the banner
if the code's not ok the div shakes (still remaining on the screen)
if you don't want to provide the code press 'cancel' and fade out the banner
Set cookie function (it works fine):
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<script type="text/javascript">
function SetPwd(c_name,value,expiredays){
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+";path=/"+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
</script>
<?php } ?>
And here must be the problem with jQuery:
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy"/>
</form>
<h3>And enjoy free access!</h3>
<a id="cancel">Cancel</a>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
if( document.cookie.indexOf("is_logged") ===-1 ){
$('#video').click(function(){
$("#login-bg").fadeIn('slow');
});
$('#cancel').click(function(){
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
}
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
});
</script>
<?php } ?>
In my opinion the value '#code' id not passed to jQuery from the form.
But I may be wrong.
Do you have any ideas. Could you make it work?
Thanks for your help.
looks to be a problem here..
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
this will not equate the way you want it to:
if( value == test )
I would suggest changing it to,
if( value == pass )
also change
$("#submit").click(
to
$("#enjoy").click(
I've changed. However, the system still does not behave as it should. When I click 'submit' the banner just disappears ( doesn't matter if the code is ok or not ).
I think the value is not passed because when I do a simple test there's any alert:
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
alert(value);
if( value == pass ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
Yes, your click handler for the submit was not correct and at the password check you've missed the quotes 'test'. (As the others already answered.)
Below is the demo of your code and here at jsFiddle. It uses the jQuery cookie plugin for the cookies, but your PHP cookies will work too. I have just no backend for the demo.
Sorry, it's not working on SO because of insecure operation, probably the cookies are not allowed here. But at jsFiddle it is working.
Also don't remove the login div with $("#login-bg").remove(); because it will be removed from DOM and you can show it again to the user. It's better to only hide it.
// if(!isset($_COOKIE['is_logged']))
$(document).ready(function () {
if (!$.cookie('is_logged')) {
console.log('not logged in, show form');
//document.cookie.indexOf("is_logged") === -1) {
//$('#video').click(function () {
//$('#code').val(''); // clear input
$("#login-bg").fadeIn('slow');
//});
$('#cancel').click(function () {
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
} else {
$('#mainContent').fadeIn('slow');
}
$('#logout').click(function () {
console.log('hide clicked');
$('#code').val(''); // clear input
$('#mainContent').hide();
$("#login-bg").fadeIn('slow');
$.removeCookie('is_logged');
});
$("#check-form").on('click', 'input[type=submit]', function (evt) {
evt.preventDefault();
var value = $('#code').val();
var pass = 'test';
if (value == pass) { // 'test') {
//SetCookie('is_logged', 'is_logged', 365 * 10)
$.cookie('is_logged', 'true', {
expires: 7
});
$('#mainContent').fadeIn('slow');
$("#login-bg").hide(); // don't remove the login section
} else {
$('#login-bg').effect("shake");
}
});
});
#login-bg {
display: none;
}
#mainContent {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy" />
</form>
<h3>And enjoy free access!</h3>
<a id="cancel" href="#">Cancel</a>
</div>
</div>
<div id="mainContent">
<strong>Login succeeded!</strong> Shown after login!!
<a id="logout" href="#">Logout</a>
</div>

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Categories

Resources