How to take value in a variable from an input text? - php

I want to take the value from text field to a variable for checking a condition
Is it possible in view? I'm using CodeIgniter.
<input type="text" id="student_gen" name="student_gen">

On form submit you can take value in javascript function like:-
var x=document.getElementbyId('student_gen').value;
If you want to do it on entering text immediately then you can call a function on onchange="myFunction()"
and in function you can take value by above method.

In action form set current_url() after submit get input in this way
$this->input->post('student_gen');
if (!$this->input->post('student_gen'))
echo 'empty field';
elseif ($this->input->post('student_gen') != 'M')
echo 'wrong value';
or You can get and check with jquery
$('#student_gen').change(function(){
if (!$(this).val() || $(this).val() != 'M')
alert('Wrong or empty value');
});

You can use jQuery:
$(document).ready(function(){
$("#student_gen").change(function(){
var x = $("#student_gen").val();
if(x=='condition'){
code..
}
});
});
or javaScript:
<script>
function myFunction() {
var x = document.getElementById("student_gen").value;
if(x=='condition'){
code..
}
}
</script>
<input type="text" id="student_gen" name="student_gen" onchange="myFunction()">

Related

Trigger JQuery function based on value of variable

I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>

How to POST data from a field with Javascript

Hi I am trying to make a page which will use the $.post method in Javascript to post the data from a live text field through to another script when the space bar is pressed. I want the data from a the page known as index.php to be posted through another file called save.php. I want to the value of txt_a textfield to to be the value of the post varible text. How would I do this? Below is my code so far...
<html>
<head>
<script type="text/javascript">
function event_a() {
if (event.keyCode == 13) {
$(document).ready(function(){
txt=$document.getElementsByName('txt_a')[0].value;
$.post("save.php",{text:txt});
};
};
}
</script>
</head>
<body>
<form method="POST" name="" action="">
<input name="txt_a" type="text" id="txt_a" onkeypress="event_a()"/>
</form>
</body>
</html>
Thanks
This should get you started:
$(function(){
$('#txt_a').keyup(function(e){
if(e.which === 13) {
$.post('save.php',{text: $(this).val()}, function(data){
//do something with the response
});
}
});
});
And in save.php:
$text = isset($_POST['text']) ? $_POST['text'] : null;
Your javascript function should look more like this:
function event_a(event) { // event needs to be defined as arg to use.
if (event.keyCode == 13) { // ready is used to trigger code when the page is ready, not needed here
var txt=$('txt_a').val(); // assuming you are using jQuery, you can access the value like this
$.post("save.php",{text:txt});
}
}
Why are you passing variable from one file to the another? Use $_SESSION to save and retrieve the set data/variable in multiple pages .

Play audio when hidden input change value

I need to play an audio file when the hidden input field changes value.
This hidden input is in the <table> which is refreshed by Ajax to update the values.
What I need to do is, (for example) when the value turns to Yes the Clap.wav needs to play, otherwise, when the value turns to Noboo.wav must play.
Anyone can give me a sample code for this or an idea?
Thank you for those who are willing to help.
Here are some of my codes
This is the hidden input field code. It is located on table with the id of connExcel on platinum.php
<input type="hidden" name="indVal" id="indVal" value=" <?php echo $objWorksheet->getCellByColumnAndRow(5, 5)->getOldCalculatedValue(); ?> ">
And here are some of my Ajax codes
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('connExcel').innerHTML=xmlHttp.responseText;
setTimeout('AutoRefresh()',100); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET","<?php if( isset( $isAdmin ) && $isAdmin == TRUE ){ echo '../../library/tosloader.php?page='. $pageID; } else { echo ../library/tosloader.php?page='. $pageID; } ?>",true);
the 'tosloader.php' just including the platinum.php to refresh the table.
in the code where you set the hidden input's value do this
$('#myHiddenID').val(myValue).trigger('change');
then just use the change event like this
$('#myHiddenID').change(function(){
var OnOff = $(this).val();
if (OnOff == "ON") { // play clap}
if (OnOff == "OFF) { //play boo}
})
Sounds like you're completely adding and removing the element from the DOM, so you'll need to watch the DOMNodeInserted event. Luckily we can bind to it. We'll assume the hidden input has a class of hiddenInput. Then we'll need to grab our source elements, aptly named <source id="yesAudio"..../> and <source id="noAudio".../> we'll use jquery's .get() method and then use the HTML5 audio api's .play(); to invoke them.
$(document).on('DOMNodeInserted', function(e){
if(e.srcElement.className == 'hiddenInput'){
if(e.srcElement.value == 'yes'){
$('#yesAudio').get().play();
}else{
$('#noAudio').get().play();
}
}
});​​​​​
I think this is what you want.
jsBin demo
HTML:
<input id="inp" type="text" value="NO" />
JS:
function checkInputValue(){
var files = { "YES": "Clap.wav", "NO": "boo.wav" };
var sound = new Audio( files[ $('#inp').val() ] );
sound.play();
}
checkInputValue(); // USE WHEREVER YOU LIKE
Or you can do like:
name your files: yes.wav and no.wav
function checkInputValue( snd ){
var sound = new Audio( snd+'.wav');
sound.play();
}
var AJAXval = ("YES").toLowerCase() ; // the returned value to lowercase
checkInputValue( AJAXval );

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Jquery appending input values - Not displaying entered values after validation

I have registration form on my website that, using jquery I append default values to, and onFocus/blur the default values hide and show accordingly.
My problem is that when the form is submitted and has kicked back errors using php validation, I am unable to show the posted values in the fields. The javascript seems to write over the posted data that is echoed using php in the input value.
When I look at the page source after posting my form I see that in the value of the input I do appear to have the posted value, the value that I want shown. Example:
<input type="text" name="first_name" value="Harry" />
PHP has done it's work in echoing the posted data into the value of my input. Then Javascript changes it so that instead of the user seeing their name (Harry in this example) they once again see the default jquery appended "First name".
This happens even though I have a value in the input.
How can I modify my Javascript to take note of the value of my input and not write over it?
This is the code so far:
$(document).ready(function() {
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
// cache references to the input elements into variables
var passwordField = $('input[name=password]');
var emailField = $('input[name=email_address]');
var firstnameField = $('input[name=first_name]');
var lastnameField = $('input[name=last_name]');
// get the default value for the fields
var emailFieldDefault = emailField.val();
var firstnameFieldDefault = firstnameField.val();
var lastnameFieldDefault = lastnameField.val();
// add a password placeholder field to the html
passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
var passwordPlaceholder = $('#passwordPlaceholder');
// show the placeholder with the prompt text and hide the actual password field
passwordPlaceholder.show();
passwordField.hide();
// when focus is placed on the placeholder hide the placeholder and show the actual password field
passwordPlaceholder.focus(function() {
passwordPlaceholder.hide();
passwordField.show();
passwordField.focus();
});
// and vice versa: hide the actual password field if no password has yet been entered
passwordField.blur(function() {
if(passwordField.val() == '') {
passwordPlaceholder.show();
passwordField.hide();
}
});
// when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
emailField.focus(function() {
if(emailField.val() == emailFieldDefault) {
emailField.val('');
}
});
emailField.blur(function() {
if(emailField.val() == '') {
emailField.val(emailFieldDefault);
}
});
firstnameField.focus(function() {
if(firstnameField.val() == firstnameFieldDefault) {
firstnameField.val('');
}
});
firstnameField.blur(function() {
if(firstnameField.val() == '') {
firstnameField.val(firstnameFieldDefault);
}
});
lastnameField.focus(function() {
if(lastnameField.val() == lastnameFieldDefault) {
lastnameField.val('');
}
});
lastnameField.blur(function() {
if(lastnameField.val() == '') {
lastnameField.val(lastnameFieldDefault);
}
});
});
$('input[name=first_name]').val('First name');
This unconditionally sets the value of that element to First Name. It's not a "only set the value if it's empty", it's "set the value to First Name, regardless of what it's in there".
You'd need something like this to preserve what's in there:
if ($('input[name=first_name]').val() == '') {
$('input[name=first_name]').val('First name');
}
instead, which would only reset the field's value if it starts out empty.
Just get some placeholder plugin, your code repeat itself too much and still does not do what you need
This is just what you need:
http://plugins.jquery.com/project/input-placeholder
With it your code will look very clear and simple, like:
<input type="text" name="first_name" placeholder="First Name" />
<input type="text" name="last_name" placeholder="Last Name" />
<input type="text" name="email_address" placeholder="Email" />
<script>
$(function(){
$('input[placeholder]').placeholder();
})
</script>
Instead all of your javascript
on ready function your are setting some values before your default values
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
so your defalut values cannot be empty
This is how i would do it so it would be more dynamic and less code.
<input type="text" name="first_name" rel="First Name" value="<?=$first_name?>" />
<input type="text" name="last_name" rel="Last Name" value="<?=$last_name?>" />
<input type="text" name="email" rel="Email" value="<?=$email?>" />
$(function(){
$('input').each(function(){
var val = $(this).val(),
rel = $(this).attr('rel');
$(this).focus(function(){
if(val === rel){
$(this).val('');
}
});
$(this).blur(function(){
if(val === ''){
$(this).val(rel);
}
});
if(val === ''){
$(this).val(rel);
}
});
});
With the minimum changes:
if($('input[name=first_name]').val()!='')
$('input[name=first_name]').val('First name');
if($('input[name=last_name]').val()!='')
$('input[name=last_name]').val('Last name');
if($('input[name=email_address]').val()!='')
$('input[name=email_address]').val('Email address');
Another cool way:
if($('input[name=first_name]').val()!='') {
$('input[name=first_name]').val('First name');
$('input[name=first_name]').class('init');
}
if($('input[name=last_name]').val()!='') {
$('input[name=last_name]').val('Last name');
$('input[name=last_name]').class('init');
}
if($('input[name=email_address]').val()!='') {
$('input[name=email_address]').val('Email address');
$('input[name=email_address]').class('init');
}
var initVals = new Array();
$("form input").each( function (i) { initVals[i] = this.value; } );
$("form input").focus( function () {
if ( $(this).hasClass("init") ){
$(this).removeClass("init");
$(this).val("");
}
} );
$("form input").blur( function (i) {
if ( $(this).val() == "" || $(this).val() == initVals[$("form input").index(this)] ){
$(this).addClass("init");
$(this).val( initVals[$("form input").index(this)] );
};
} );
Don't forget to use hasClass("init") or similar to avoid sending inputs with its default value.

Categories