I want the switch button to remember selected option. Because when I refresh browser my selection is resetting.. How can I do that?
Here is my code:
HTML:
<input type="button" value="Tak" onclick="return change(this);" />
JS:
<script>
function change( el )
{
if ( el.value === "Tak" ){
el.value = "Nie";
}else{
el.value = "Tak";
}
}
</script>
Client side values will reset when you refresh the browser.
You need to store in cookie or session for that
Include this to simply set and get cookie.
Something like:
<head>
<script src="path/to/jquery.js"></script>
<script src="path/to/jquery.cookie.js"></script>
</head>
...
<input type="button" value="Tak" onclick="return setValue(this)" id="btn"/>
Now you can get/set cookie and change input value whit no problem, something like:
function setValue(elem){
if(elem.value == "Tak"){
elem.value = "Nie";
$.cookie("btnState", true);
} else {
elem.value = "Tak";
$.cookie("btnState", false);
}
}
function getValue(){
var c = $.cookie("btnState");
if(c != null){
if(c){
$('#btn').val("Nie");
} else {
$('#btn').val("Tak");
}
} else {
//first page view
$.cookie("btnState", true);
$('#btn').val("Nie");
}
}
trigger getValue() on page load to check cookie value and set input value
EDIT:
To fire a function on page load use jQuery .ready function like this:
<script>
$(document).ready(function() {
getValue();
});
</script>
jQuery .ready documentation.
Here is a example in jsfiddle
Related
how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work
Heres the code
<form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)">
</form>
<div id="canvasDiv" width="500" height="10"></div>
<script type="text/javascript" src="robotti.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 500, 500);
document.getElementById("canvasDiv").onmousedown = function() {
jump(); }
//document.getElementById("canvasDiv").onkeypress = function() {
//move(); }
document.getElementById("canvasDiv").window.onkeypress = function(event) {
if (event.keyCode == 41) {
move();
}
}
</script>
This should work -:
var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
jump();
getElementById("canvasDiv").value = "";
}
Please use onkeyup instead of onkeydown
<!DOCTYPE html>
<html>
<body>
<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">
<script>
function keyCode(e) {
var text = (document.getElementById("canvasDiv").value).toLowerCase();
if(text == 'jump' || text == 'move'){
//call jump function here
alert("jump");
}
}
</script>
</body>
</html>
You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.
document.querySelector('input[type="text"]').addEventListener('keyup', function() {
switch (this.value) {
case 'move':
console.log('move!'); // Your actual function here
this.value = ''; // Reset value
break;
case 'jump':
console.log('jump!'); // Your actual function here
this.value = '' // Reset value
break;
}
});
Command the robot!: <input type="text" size="50">
Further reading:
Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector
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>
i don't know why it's n't work , want according to check box value redirect to page or do nothing . and this is the code
<html>
<body>
<form onsubmit= "lol()" >
Checkbox: <input type="checkbox" id="myCheck">
<input type="submit" value="Submit">
</form>
<script>
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location="http://www.google.com";
}
else
{
// want do nothing and stay at same page .
}
}
</script>
</body>
</html>
how can i do it
Two things you need to here if you want to keep the form not doing anything in false condition.
When you call the function you need to use return. So that the form won't submit until it got the return true value.
In your function else part you need to mentioned return=false. It will stop the form submitting.
Javascript:
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.href="http://www.google.com";
}
else
{
return false;
}
}
HTML
<form onsubmit="return lol()">
Checkbox: <input type="checkbox" id="myCheck"/>
<input type="submit" value="Submit" />
</form>
JSFIDDLE DEMO
You can do it in jquery
$('#myCheck').click(function() {
if($('#myCheck').is(':checked')){
window.location = 'http://www.naveedramzan.com';
}
});
Modify your function:
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.href="http://www.google.com";
}
else
{
// want do nothing and stay at same page .
}
}
To redirect from one page to another, you use window.location.href, not window.location.
you can also use location.assign() function
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.assign("http://www.google.com");
}
else
{
// want do nothing and stay at same page .
}
}
You don't want to use a post for this, everything can be handled client side:
<body>
Checkbox: <input type="checkbox" id="myCheck">
<input type="button" value="Submit" onclick="lol()">
<script>
function lol() {
if (document.getElementById("myCheck").checked === true) {
window.location = "http://www.google.com";
}
else {
// want do nothing and stay at same page .
alert("staying on page");
}
}
</script>
</body>
I have member status select box in that i have open,read,close option is there.So when i'm selecting open or read and click update button it will updateing something.and i'm selecting close it display dialog box(Are you sure want close this)if yes it goes to some page or goes to no page.(I want to dispaly confirm box only particular value(22 only).
Anybody help on this one(js or jquery).It is smarty application
Here is my code
<html>
<head>
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val == '22') {
var state = confirm("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
</head>
<body>
<form method="post" action="/admin/member-modify-{$member->id}">
<label>Member state</label>
<select name="sel_state" class="validate" id="sel_state">
<option value=1>open</option>
<option value=2>read</option>
<option value=22>close</option>
</select>
<input name="submit" value="Validate" id="member_state_submit" type="submit" class="submit" Onclick="showClose();" />
</form>
</body>
</html>
All what you have to do is to wrap your JS code within {literal}{/literal} tags like this :
{literal}
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val=='22') {
var state = confirm ("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
{/literal}
In Smarty, anything within {literal}{/literal} tags is not interpreted, but displayed as-is. This will avoid interfering with the template delimiter syntax. Check the documentation.
This is simple with jquery
var value = $('#selector').text()
if (value == 22){
//do something here
}
In jQuery, is there a simple way to test if any of a form's elements have changed?
Say I have a form and I have a button with the following click() event:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
How would I test if the form has changed since it was loaded?
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() {
var form_original_data = $("#myform").serialize();
$("#mybutton").click(function() {
if ($("#myform").serialize() != form_original_data) {
// Something changed
}
});
});
A real time and simple solution:
$('form').on('keyup change paste', 'input, select, textarea', function(){
console.log('Form changed!');
});
You can use multiple selectors to attach a callback to the change event for any form element.
$("input, select").change(function(){
// Something changed
});
EDIT
Since you mentioned you only need this for a click, you can simply modify my original code to this:
$("input, select").click(function(){
// A form element was clicked
});
EDIT #2
Ok, you can set a global that is set once something has been changed like this:
var FORM_HAS_CHANGED = false;
$('#mybutton').click(function() {
if (FORM_HAS_CHANGED) {
// The form has changed
}
});
$("input, select").change(function(){
FORM_HAS_CHANGED = true;
});
Looking at the updated question try something like
$('input, textarea, select').each(function(){
$(this).data("val", $(this).val());
});
$('#button').click(function() {
$('input, textarea, select').each(function(){
if($(this).data("val")!==$(this).val()) alert("Things Changed");
});
});
For the original question use something like
$('input').change(function() {
alert("Things have changed!");
});
$('form :input').change(function() {
// Something has changed
});
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed.
Each type of input has it's own property name. For example
for text/textarea it's defaultValue
for select it's defaultSelect
for checkbox/radio it's defaultChecked
Here is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable
var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
var newformStr = JSON.stringify($("#form").serializeArray());
if (formStr != newformStr){
...
formChangedfunct();
...
}
else {
...
formUnchangedfunct();
...
}
}
You need jQuery Form Observe plugin. That's what you are looking for.
Extending Udi's answer, this only checks on form submission, not on every input change.
$(document).ready( function () {
var form_data = $('#myform').serialize();
$('#myform').submit(function () {
if ( form_data == $(this).serialize() ) {
alert('no change');
} else {
alert('change');
}
});
});
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
$("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
<input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
<input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
<input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
<select name="one_d">
<option value="111111">111111</option>
<option value="222222">222222</option>
<option value="333333">333333</option>
</select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
<input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
<input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
<input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
<input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
<input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
<input type="text" name="two_f" id="two_e" value="IIIIIIII" />
<select name="two_g">
<option value="444444">444444</option>
<option value="555555">555555</option>
<option value="666666">666666</option>
</select>
</form>
<h2>Result</h2>
<div id="result">
<h2>Click on a field..</h2>
</div>
In addition to above #JoeD's answer.
If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
// A form element was clicked
});
Try this:
<script>
var form_original_data = $("form").serialize();
var form_submit=false;
$('[type="submit"]').click(function() {
form_submit=true;
});
window.onbeforeunload = function() {
//console.log($("form").submit());
if ($("form").serialize() != form_original_data && form_submit==false) {
return "Do you really want to leave without saving?";
}
};
</script>
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});