I'm having a bit of a confusing question but hopefully you'll get what I mean:
In my website I'm trying to implement a select box which is updated based on the value from a previous select box. For that I'm using a javascript that takes the values. For example an option from the select box looks like this:
<option value="22"> Apple </option>
I need the value in order to filter the select boxes but in my PHP script I need to get that 'Apple' text. Is there a way to do that?
Sorry for the noob question but web development is new for me.
Edit:
This is the java script I'm using for filtering the second select box:
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
If I try to change this 'value' in the filter function to some other attribute it doesn't work for some reason. I don't know JavaScript at all.
Try this
var pName = document.getElementById('selectname');
var name = pName.options[pName.selectedIndex].text;
Send the name value to your php script by hidden form field or ajax request,
It will contain the text of the option
try this
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
or
this.options[this.selectedIndex].innerHTML
fruits_array.php
<?php
$fruits= array(
22 => 'apple' ,
23 => 'orange'
);
form_handler.php
if( isset($_POST['chosen_fruit']) && (int)$_POST['chosen_fruit'] > 0 ){
include 'fruits_array.php';
echo you chose ' . $fruits[$_POST['chosen_fruit'];
}
pick_your_fruit.php
<form action='form_handler.php' method= POST>
<select name='chosen_fruit'>
<?php
include 'fruits_array.php';
foreach($fruits as $key=$fruit)
echo '<option value=' . $key . '>' . $fruit .'</option>' . PHP_EOL ;
?>
<input type=submit />
</form>
Give this a try. Maintain an array of fruit in one place. Include it where you need it. If necessary that array could be from a database.
Use the array to
generate the form elements
generate the message
But, essentially, transferring the number of the key between the form and the form handler eases the thorny question of validating the incoming data.
DRY. Dont Repeat Yourself. Now if you have 99 fruit, and you add another, you only add it in one place.
(the main thing missing is the handling of a fruit number which does not exist, which probably means someone is tampering with you input form, leave that for another question, eh?)
Try like this
<form method="post" action="getvalue.php">
<select name="fruit">
<option value="">select the option</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Mango</option>
</select>
</form>
<?php
$option = array('1'=>'Apple','2'=>'Banana','3'=>'Mango');
echo $option[$_POST['fruit']];
?>
The Apple is not passed to the server, only your value, in this case 23. You can see that when you change your formular method to GET, it will look like script.php?some_select=23.
Two solutions to solve it:
The first one (the easy one) would be:
<option value="Apple" data-filterid="22"> Apple </option>
And in your js:
var options = $(this).data('options').filter('[data-filterid=' + id + ']');
So you get Apple in your php script instead of 22. You could then filter it in javascript by accessing data-filterid instead of value.
The second solution would be to store an associative dictionary which maps the value to the number, e.g.:
<?php
$mapped = array(22 => "Apple", 23=>"Orange");
$value = $mapped[$_GET['option_name']];
Related
I need to split a select input in two parts in order to use one part for dynamic form creation on the same page and the second part to be sent to the receiving form.
This is what I have now to dynamically create the div below based on the select input selection:
$a = 0;
while ($row = mysql_fetch_array($result)) {
$people_array[$a] = array(
"ID" => $row['ID'],
"event" => $row['name'],
"time_needed" => $row['time_needed'],
);
$a = $a + 1;
}
$count = count($people_array);
<form>
<?php for($p=0,$p<$count,p++){
$segment_id = $people_array[$p][ID]; ?>
<select name="name_segment" id="name_segment">
<option value="female" >
<?php echo $people_array[$p][name]; ?>
</option>
<option value="male" >
<?php echo $people_array[$p][name]; ?>
</option>
</select>
<?php } ?>
</form>
<div id="name_segment_female" class="name_segment_input" style="display:none;">
Allow at least 30 extra minutes for bathroom usage.
</div>
<div id="name_segment_male" class="name_segment_input" style="display:none;">
No extra bathroom time needed.
</div>
and the javascript
<script>
$("#name_segment").change(function() {
var name_segment = $(this).val();
$(".name_segment_input").hide();
$("#name_segment_" + name_segment).show("slow");
});
</script>
Searching here on stackoverflow, I have found this post that got me started with this: <option value="{type:'amount',segment_id:'<?php echo $segment_id; ?>'} >. I just need to know how I can split this object up with javascript before submitting the page. I need to have the hidden div display dynamically using the same value from the option input as a more specific value that will be sent to the receiving page for the form.
First I changed options values all to be the same length for simplicity.
for example I left "male" the same but changed female to "fmle"
Then I changed the javascript:
$("#name_segment").change(function() {
var name_segment = $(this).val();
var local_segment = name_segment.slice(0,4);
$(".name_segment_input").hide();
$("#name_segment_" + local_segment).show("slow");
});
to parse out just the four letter section and use similarly as the original design. Then I changed the options values to <option value="fmle_<?php echo $segment_id; ?>" >. The segment_id will be parsed out server side after the submission of the form.
If completely necessary we can do a little more work to only send the segment_id as the original question asked but this will achieve the desired objective.
I have a form with 4 dropdowns and a submit button. When a user clicks the submit button I want to go to my controller handling the input/output giving the users choices, but with a correct URI.
The dropdowns are dynamically generated from Ajax depending on the users choices, bar the first dropdown. They are working absolutely fine.
The method handling the user input is located in this controller: /app/controllers/shop/kategorier, index method looks like this:
public function index($fabrikat, $type, $model, $produktnr = '0')
{
// get all the data from the model
$data['all'] = $this->fetch->get_kategorier($fabrikat, $type, $model, $produktnr);
print_r($data['all']);
}
My goal is this: When users hit the submit button, I wan't them to view the page with that exact URL including the parameters, eg. http://app.com/shop/kategorier/index/LG/WASH/FL9834X/0/ That's all I really want.
Note: Accessing this URL manually works fine, and the controller/model handles the parameters as they should.
How do I accomplish this? I tried two things, they both failed. Sort of.
I tried with jQuery, and generated a encodedURL string with all the
parameters with a '/' delimiter, and changed the .attr('href') on
submit. But that was a nightmare, since some of the $model's can be
eg. 'CE1000C-T / XEE' etc.
I tried to make a 'proxy' method in the Kategorier
controller taking all the input->posts and appending them to a
redirect('kategorier/'.$fabrikat.'/'.$etc), but that was rather
stupid.
I would rather not use query strings like /kategorier?fabrikat=LG&type=WASH etc
My form looks like this:
<?php echo form_open('shop/kategorier/'); ?>
<select id="fabrikat" name="fabrikat">
<option name="0">Vælg Fabrikat</option>
<?php foreach ($fabrikater as $f) : ?>
<option value="<?php echo $f->Fabrikat; ?>" name="<?php echo $f->Fabrikat; ?>"><?php echo $f->Fabrikat; ?></option>
<?php endforeach; ?>
</select>
<select id="type" name="type">
</select>
<select id="model" name="model">
</select>
<div id="produktnummer-wrap" style="display:none">
<select id="produktnummer" name="produktnummer">
<option name="0" value="">Vælg Produktnummer</option>
</select>
</div>
<?php echo form_submit('findparts', 'Find Reservedele'); ?>
<?php echo form_close(); ?>
I believe I'm somehow overcomplicating things, but right now I can't think straight. I will be more than happy to elaborate anything.
I really hope someone is able to help me out, thanks in advance.
You can't really achieve this without using some JavaScript:
<script type="text/javascript">
function update_selections()
{
var base_url = '<?php echo site_url('shop/kategorier/index'); ?>/' + $('#fabrikat').val() + '/' + $('#type').val() + '/' + $('#model').val();
if( $('#produktnummer').val() != "" )
{
base_url = base_url + '/' + $('#produktnummer').val();
}
document.location.href = base_url;
}
</script>
Remove the current form and use an onclick event to trigger this.
#Repox I did figure out an approach last night which was actually pretty similar to your solution. Here's what I did:
$("#find-btn").on("click", function() {
var fab = $("select#fabrikat").val();
var type = $("select#type").val();
var model = $("select#model").val();
var produktnummer = $("select#produktnummer").val();
// we have to replace spaces in models and types
model = model.replace(/\s+/g, '-');
type = type.replace(/\s+/g, '-');
// produktnummer can be empty
produktnummer = (produktnummer === '') ? "0" : produktnummer;
// we also have to URI encode the model and prodnr since it
// can be horror strings like 'xy762 / ø23'
model = encodeURIComponent(model);
produktnummer = encodeURIComponent(produktnummer);
// our url string to update the href
var url = fab + '/' + type + '/' + model + '/' + produktnummer;
// update the href with the specific parameters
$(this).attr("href", "http://app.dev/kategorier/index/"+url);
});
Although I need to be very wary when handling the parameters in my controllers and models, they need to be encoded and decoded correctly afterwards. A slight portion of the model strings could be something like:
'EX+ 340-34 / Ø14' OR '77773+ -/ 23IK'
Which isn't ideal with the decoding in my controller using str_replace('-', ' ', $str); I therefore need to examine lots of the data before choosing a replacement character.
However, this is probably the best solution if one wishes to do this without having to use query strings in Codeigniter.
I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>
I've read other questions on here that dealt with what I am looking for. But it still did not help me.
I want to have multiple values in an option of the select tag of a form that will be posting the information onto a different file that is viewable to the visitor by iframe. Example of what I am trying to do:
The following is on the file: Form.php
<div>
<form action"blank.php" method="post" target="box">
<select name="g1">
<option name="g1" value="Value 1, Value 2"> Text </option>
<option name="g1" value="Value 1, Value 2"> Text Blah </option>
</select>
<input type="submit" />
</form>
</div>
<iframe src="blank.php" name="box"></iframe>
The Following is a long the lines of what I want to appear on the: blank.php which is visible by iframe.
Option 1 or 2 value's should appear like this
[ Value 1 ] [ Value 2 ]
An Example:
Its a drop down menu that will post two seperate values when you select one option.
Like if I selected an option that says Hola - hello and it will post:
[Hola] means [Hello].
and the option tag would have the values as:
<option name="g1" value="Hola, Hello">Hola - Hello</option>
Sounds like you want to build an array of your form fields where multiple values are allowed. Read the PHP manual for more.
From the manual:
How do I get all the results from a select multiple HTML tag?
The
select multiple tag in an HTML construct allows users to select
multiple items from a list. These items are then passed to the action
handler for the form. The problem is that they are all passed with the
same widget name. I.e.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable.
The solution is to use PHP's "array from form element" feature. The
following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a
value to var[] adds an item to the array. The first item becomes
$var[0], the next $var[1], etc. The count() function can be used to
determine how many options were selected, and the sort() function can
be used to sort the option array if necessary. Note that if you are
using JavaScript the [] on the element name might cause you problems
when you try to refer to the element by name. Use it's numerical form
element ID instead, or enclose the variable name in single quotes and
use that as the index to the elements array, for example:
variable = document.forms[0].elements['var[]'];
First of all, you don't need a name attribute on each of your <option> elements. Just the <select> box.
Second of all, I think all you need is the handy dandy explode function. You'll get the value like this...
$values = $_POST['g1'];
...and then split them into an array like this...
$values = explode(', ', $values);
...and finally just access the values like so:
$value1 = $values[0];
$value2 = $values[1];
I know that this is in the PHP section, but what you are trying to do would be much easier to achieve with javascript. If you change the iframe tags to:
<div id="valueDisplay"></div>
and add an ID and listener to the select
<select name="g1" id="dropDown" onchange="showValues()">
<option name="g1" value="1"> Text </option>
<option name="g1" value="2"> Text Blah </option>
</select>
You just write a little script like this and put it in the body somewhere:
<script type="text/javascript">
function showValues(){
var outDiv = document.getElementById('valueDisplay');
var selectValue = document.getElementById('dropDown').value;
var divText;
if(selectValue == 1) divText = '[ Value 1 ][ Value 2 ]';
if(selectValue == 2) divText = '[ Value 1 ][ Value 2 ]';
outDiv.innerHTML = divText;
}
</script>
To achieve what you are trying to do with iframes would be more difficult. It would require you to use javascript/jquery to post the data within the iframe.
Note that using onchange="" is no longer the accepted method of adding listeners. It is just easier if you are not familiar with javascript.
I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed