.trigger('change') on page load to persist jQuery driven reveal of elements - php

I have various input elements which control the "hidden" state of various dependent divs.
The type of input varies, and the value which the input must equal (to reveal the div) also varies. I have used php to write javascript (jQuery) depending on these factors, by using the general piece of code:
php
$remove .=" $('#".$id."').removeClass('hide');";
$add .="$('#".$id."').addClass('hide');";
...
$jquery ="
$(\"input[name$='$name."']\").change(function(){
if(this.value == '".$key_val."') {
".$remove."
} else {
".$add."
}
}).trigger('change');
";
Note: the $remove and $add variables are built using concatenation and loops as there may be several hidden elements which need to be hidden or revealed (hence the .=)
This generally results in a piece of code on page (actual code) such as:
jQuery
$(document).ready(function(){
$("input[name$='q_32']").change(function(){
if(this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
}).trigger('change');
$("input[name$='q_32']").change(function(){
if(this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
}).trigger('change');
});
On the page this works well: when the radio button in question (input name q_32) is changed, the corresponding element is hidden or revealed.
The .trigger('change'); is there because I want the divs to be hidden or revealed on page load having set the checked state server side.
The following is the HTML is how the page now loads:
HTML
<span>Yes</span>
<input type="radio" id="q_32_Yes" value="Yes" name="q_32" checked="">
<span>No</span>
<input type="radio" id="q_32_No" value="No" name="q_32">
<div id="qu_33" class="hide">...</div>
<div id="qu_34" class="">...</div>
i.e. the radio button is loading in the checked state for Yes, but the incorrect div is being revealed - so it is triggering, however it seems that the value is being read wrong.

The script should be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
});
$("input[name$='q_32']").change(function () {
if (this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
});
$("input[name$='q_32']").filter(':checked').change()
});
Demo: Fiddle
a more correct script will be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
$('#qu_34').addClass('hide');
} else {
$('#qu_33').addClass('hide');
$('#qu_34').removeClass('hide');
}
}).filter(':checked').change();
});
Demo: Fiddle
If you have more instances of the same code then try this

Related

Prevent inspect element in text field

Here is my input field disabled code
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
How can i prevent inspect element option in this field?
No it's not possible.
Code inspectors are designed for debugging HTML and Javascript. They will always do show the live DOM object of web page. It means that it reveals the HTML code of everything you see on the page, even if they're generated by Javascript.
As mentioned in other answers, it can't be prevented fully, once it is in the browser, user can manipulate it.
Rather than thinking how to prevent the inspect element or dev tools being used on your input, you should think about your goal, what do you want to achieve with this?
If you want to prevent from input value being changed, use some hash generated on server side, that includes value from your staffid field and store it in hidden input.
When user submits the form, just regenerate hash using staffid value and hash value from input. If they don't match, user has manipulated the staffid input manually.
Example:
<input type="text" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />
<input type="hidden" name="hash" value="<?php echo md5($employeeworks[0]['employeeCode'] . 'some salt to avoid user just generating hash with md5 using value only'); ?> />
and then on submission:
$staffid = filter_input(INPUT_POST, 'staffid');
$hash_input = filter_input(INPUT_POST,'hash');
$hash_check = md5($staffid . 'some salt to avoid user just generating hash with md5 using value only');
if($hash_input !== $hash_check){
//looks like the user manipulated staffid value, throw a validation error
}
You can prevent inspect by right click.
This way to prevent right click
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
If user press F12 and click arrow button and inspect, it still ok.
You also can prevent F12 by this code
document.onkeydown = function(e) {
if(event.keyCode == 123) { //F12 keycode is 123
return false;
}
}
Actually, you can not restrict user to check inspect element of any specific element but you can disable completely. Check below code which will not allow user to open debugger and not even page source.
document.onkeydown = function(e) {
if(e.keyCode == 123) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
e.preventDefault();
return false;
}
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
e.preventDefault();
return false;
}
}
But this code also has some missings as well. Hope it helps you.
Try This,
<input type="text" oncontextmenu="return false;" class="empl_date form-control" id="staffid" name="staffid" value="<?php echo $employeeworks[0]['employeeCode'];?>" arsley-maxlength="6" placeholder=" Schedule Date" disabled />

Validate form fields in sequences

I have a multi-step order form built in this manner:
Step 1: Choose category via radio button
The "Next" button is just an image that has an onclick function hides the current div with the radio buttons, and displays a new div with the next step in the process.
Step 2: Textarea, checkbox -> Dynamic price
Contains a textarea, a dynamic price, and four checkboxes. The price changes depending on the number of characters in the textarea and the choices in the checkboxes. JQuery script is used in order to do that. Again, the "Next" button is just an image that upon activating the onclick function hides the current div, and displays the div containing the next step in the form.
Step 3: Personal Data
And here is my problem. Here where the user inserts name, email and so on. The "Next" button is again just an image that upon activating the onclick function hides the current div and displays the div containing the next step. How do i make the form fields in this step required in order to allow the user to advance to the next step. The code i have for hiding and showing the divs is as follows:
<script type="text/javascript">
function toggleDiv(id, flagit) {
if (flagit == "1") {
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else`if (flagit == "0") {
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"`
}
}
//-->
</script>
That is a horrible (and wrong) piece of old code.
here is an update that actually still handles Netscape4 (the layers part)
You need to show me the rest of the script where you toggle. You need to add validation to
THAT part, not the toggle.
For example, using
<form onsubmit="return validate(this)">
and
<input type="image" src="next.png" />
you can do this (plain JavaScript, the show and hide in jQuery is shown elsewhere on the page):
var currentStep=1;
function toggleDiv(id,flagit) {
if (document.getElementById) document.getElementById(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.all) document.all(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.layers) document.layers[id].visibility = (flagit)?"show":"hide";
}
function validate(theForm) {
if (currentStep == 1) {
if (theForm.category.value....) {
alert("Error in category");
return false;
}
currentStep++;
toggleDiv("part1",0);
toggleDiv("part2",1);
return false; // do not submit
}
if (currentStep == 2) {
if (theForm.price.value....) {
alert("Error in price");
return false
}
currentStep++;
toggleDiv("part2",0);
toggleDiv("part3",1);
return false; // do not submit
}
if (currentStep == 3) {
if (theForm.name.value....) {
alert("Error in name");
return false
}
return true; // submit
}
}
Well, since you have tagged your question with jQuery, why not actualy use it and let jquery handle all platform specific issues.
function toggleDiv(id,flagit) {
if( flagit ) {
$("#"+id).show();
} else {
$("#"+id).hide();
}
}
Let me know if this works.

onchange won't print out error for empty input

I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

checkbox state should retain state to hide/unhide text on pageload

as a follow up to this question, while the checkbox value is stored on pageload, the text is displayed on pageload, even if the checkbox is unchecked. the text should hide/display only if the user has unchecked/checked the checkbox, throughout the session or till he closes the browser.
js code which stores the checkbox state:
function getStorage(key_prefix) {
// this function will return us an object with a "set" and "get" method
// using either localStorage if available, or defaulting to document.cookie
if (window.localStorage) {
// use localStorage:
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
// use document.cookie:
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = decodeURIComponent(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
// a key prefix is used for the cookie/storage
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
$('#ab_'+this.id).toggle($(this).is(':checked'));
// save the data on change
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
// on load, set the value to what we read from storage:
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val) $(this).trigger('change');
});
});
this ^code should work, but it while it retains the state of the checkbox, it doesn't for the text. is it because the text is being called from a php page?
html:
$(document).ready(function() {
$("#bquote").load("quotes_in.php");
});
.. ...
<div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
</div>
.. ...
<blockquote id="bquote">
</blockquote>
php:
public function formatQuotes($row)
{
return "<p id=\"ab_name\">" . $this->h($row['cName']) . "</p><br />"
. "<p id=\"ab_reference\">" . $this->h($row['vReference']) . "</p>";
}
You need to trigger the change() event on document ready after the p elements are generated.
Edit:
If placing the change trigger after the .load() call does not work, then that is probably due to the ajax request not being completed yet at the point of triggering. This can be solved by using callback parameter of .load(). Therefore, the code should look something like:
$(document).ready(function() {
$("#bquote").load("quotes_in.php", function() {
// create the P elements
// trigger the change() event
});
});

Categories