Change link url with value from dropdown list - php

I'm trying to change a series of links by inserting values from a dropdown box. I found this straight forward to do with php (code below) but I'd like to be able to change the links without 1) having a page refresh (these links are near the bottom of the homepage) and 2) without a submit button if possible.
Here is the php code:
<form name="test" action="<?php echo
htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<select name="county" id="select13">
<option value="All">All</option>
<option value="County1">County1</option>
<option value="County_2">County 2</option>
...
</select>
<input type="submit" name="submit" value="Set County">
</form>
<?php
if(isset($_POST['submit']))
{
$county = $_POST['county'];
$www = "http://www.website.com/";
$food = "/topics/Food/programs.aspx";
$meals = "/topics/Meals/programs.aspx";
....
echo "<a href=$www/$county/$food>Food</a><br>";
echo "<a href=$www/$county/$meals>Meals</a><br>";
The above code works fine, but requires a page refresh. I was attempting to use jquery to just take a list of links, such as:
Food
And just replace "county" with the value from a dropdown box.
function changelinks(){
var countyvals = $("#county").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = this.href.replace(/^http:\/\/www\.webpage\.com\/topics\//,"http://www.webpage.com/topics/"+countyvals);
});}
The above code works fine changing the link once, but after the link is changed I can't target the links anymore. I just started teaching myself jquery today, so I've no idea where to look for a better solution.
What might be the best way of changing these links?
Should I try some ajax on the php code, or is there a better/simpler solution through jquery?
THANKS!

I would use HTML 5 data attributes. Have a data-relativeurl attribute on each anchor of interest, then you can use
function changelinks(){
var countyvals = $("#selector13").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = "http://www.webpage.com/" + countyvals + $(this).attr('data-relativeurl');
});}

Related

Show DIV Text based on Multiple Selections jQuery and PHP

I have tried to search google and here about my question but havent found the exact answer which I could use. So I am asking here. Hope to find help.
I have some input fields in a form and want to show a DIV using jQuery. The details (pseudo-logic) are as follows.
V1: <input type="radio" name="rad" value="v1" />
V2: <input type="radio" name="rad" value="v2" />
<select name="sel">
<option value="o1">o1</option>
<option value="o2">o2</option>
</select>
Now, based on selection, the jQuery will generate the text in an initially empty hidden div based on data filled in form fields.
For example, as it may be shown
<div id="d1">
The calculated value for rad(o1) & o2 & t1 is "value1"
</div>
If it was only for PHP, the simple code I could use, to be processed in another php file, would be (using mysql query, and I am aware of real escape strings, just not mentioning here),
$radioBtn = $_POST['rad'];
$selDrpDn = $_POST['sel'];
$textData = $_POST['t1'];
//Using this query,
$queryString = mysql_query("SELECT * FROM mobiles WHERE jobType = '$radioBTN' AND modelName = '$selDrpDn' AND compName = '$textData'");
Not sure if this answers your question...
$(function() {
$("select[name='sel'], input[name='rad']").on("change",function() {
$('#d1').html("You selected : " + this.value).show();
}
});
that's using the form code and div sample you gave above.

One submit button to send form data to one PHP destination OR another

I' new to HTML and PHP and was wondering if anyone out there could help me with a question... I'm trying to code a form that submits a selection from one menu OR another and, depending on which is chosen sends the data to one of two different PHP pages.
<form id="form1" method="post" action="">
<label for="SubjectID">Text Books by Subject</label>
</p>
<p>
<select "name="SubjectID" id="SubjectID">
<?php do { ?>
<option value="<?php echo $row_rsSubject['SubjectID']?>"><?php echo $row_rsSubject['SubjectName']?></option>
<?php } while ($row_rsSubject = mysql_fetch_assoc($rsSubject));
$rows = mysql_num_rows($rsSubject);
if($rows > 0) {
mysql_data_seek($rsSubject, 0);
$row_rsSubject = mysql_fetch_assoc($rsSubject);
} ?>
</select>
</p>
<p>
——— OR ———
</p>
<p>
<select name="CourseID" id="CourseID">
<?php do { ?>
<option value="<?php echo $row_rsCourse['CourseID']?>"><?php echo $row_rsCourse['CourseID']?></option>
<?php } while ($row_rsCourse = mysql_fetch_assoc($rsCourse));
$rows = mysql_num_rows($rsCourse);
if($rows > 0) {
mysql_data_seek($rsCourse, 0);
$row_rsCourse = mysql_fetch_assoc($rsCourse);
} ?>
</select>
</p>
<p>
<label for="CourseID">Text Books by Course</label>
</form>
So, the action should be (depending on which menu the user selects from) that the form submits to either subject.php or course.php, and I can't figure out how to do that with a single submit button. Can anyone help me?
first set onchange event to select:
<select name="CourseID" id="CourseID" onchange='myFunc(this)'>
Then:
<script>
function myFunc(element){
// set the form action depends on option chosen
// element.setAttribute('action', 'yourPageLink' );
}
</script>
You could update the action attribute with javascript when the user changes his selection, directing him to the relevant page.
Otherwise, why not submit to a single function and depending on the users selection call the relevant function?
Honestly I would use jquery's $.post to do this. To the best of my knowledge you can't really do that with straight html, and php is executed before the page loads so that's no help. With JQuery you could set an action to the button to call a function. Then your function could check the value of the select and pass the proper url to the $.post function.
You can read about that particular jquery function here: http://api.jquery.com/jQuery.post/
If you're not familiar with JQuery it's really easy to use with just a bit of reading if you're good with JavaScript.
Why not have a radio button in the form whose posted form value is processed by a central PHP form handler? That way, depending on what is entered on the radio button, you can process the request as necessary.
This might not be the answer you are looking for, but I am not clear if you want the user to be able to alter the destination or what.

When POST'ing Dropdowns values, only first value gets posted, second is null (using JSCRIPT, PHP)

EDIT: My main code no longer works, should this function work?
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script>
var second_choice = $('#second-choice').val();
$("#first-choice").change(function() {
$("$second-choice").load("findModel.php?choice=" + $("#first-choice").val());
});
</script>
Here is the associated PHP File:
<?php
include 'dbc.php';
$choice = mysql_real_escape_string($_GET['choice']);
$query="SELECT * FROM `cars` WHERE `DVLAMake`='$choice'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'DVLAModel'} . "</option>";
}
?>
The database connection works.
#
On load a PHP file populates my first dropdown:
<form name="indexSearch" action="searchResults.php" method="POST">
<select id="first-choice">
<option selected value="base">Please Select</option>
<option value="VAUXHALL">VAUXHALL</option>
<?php
$sql="SELECT DISTINCT `DVLAMake` FROM `cars`";
$result = mysql_query($sql);
while ($data=mysql_fetch_assoc($result))
{
echo "<option value =\"{$data[DVLAMake]}\" >{$data[DVLAMake]}</option>\n";
}
?>
</select>
<select id="second-choice">
<option>Please choose from above</option>
</select>
<br />
<input type="submit" style="font-size:14px; padding:3;"value="Submit" size="20" />
</form>
That works, and then on choosing the value it calls a function which then fills the second with options which I can choose from. However when I post the form, it doesn't take the second dropdown selected value through it's just empty but it does take the first dropdown value selected value.
Any reason why?
The problem is that the second select tag does not have name attribute. if it lies in the form you will get the request via post only if the attribute has name. if you are using jquery you can simply fetch value by id then post it via ajax. select like this in jquery.
var second_choice = $('#second-choice').val();
How are you changing the selected value? Using e.g. ajax? And how are you sending your data? Using ajax or simple POST with page reload?
If you're changing something using ajax your data need to be send by ajax. Because without it you will don't send your data generated by JS but this generated by your PHP script.
You wrote
$("$second-choice").load("findModel.php?choice=" + $("#first-choice").val());
instead of:
$("#second-choice").load("findModel.php?choice=" + $("#first-choice").val());
$ -> #

Questions regarding forms and php (clearing form, live refresh, multiline)

I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>

php how to grab the selected value from a drop down list?

<select name="gamelist" id="gamelist">
<option value="1">Backgammon</option>
<option value="2">Chess</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit" />
i want to grab the selected value and place in in a var
any idea?
thanks
Depends on your form tag.
<form method="post">
Will pass the value to $_POST['gamelist']
While
<form method="get">
Will pass the value to $_GET['gamelist']
Ofcourse, only after hitting the submit button. As morgar stated, this is pretty basic form procession. I doubt you've used google or followed a tutorial, this is almost one of the first things one learn when working with forms and PHP. We arent here to give you full solutions, take this as an example and create the full page yourself:
if($_SERVER['REQUEST_METHOD'] == "Y") {
$choice = $_Y['gamelist'];
// other stuff you want to do with the gamelist value
} else {
echo '<form method="Y" action="file.php">';
// the rest of your form
echo '</form>';
}
Replace Y with either GET or POST.
$choice = $_REQUEST['gamelist']; //works with get or post
$choice = $_POST['gamelist']
if it is a POST, or $_GET if not.

Categories