I was seeking help in a previous threat, and the advice lead me in a different direction. As such, the thread died. I've made a lot of progress, and I feel very close to my answer.
I have two files:
Local file: maps.php
Remote file: maps_append.php
maps.php has a form select tag. I need jQuery to get the value of whatever option is select and load the remote URL (maps_append.php) with maps_append.php?cmd=(value)
What I have is:
<form method="post" action="maps.php">
<td colspan="3">
<select id="cmdview" name="cmd">
<option value=""></option>
<option value="commdata" {if $cmdOn == "commdata"}selected="true"{/if}>Communications</option>
<option value="contacts" {if $cmdOn == "contacts"}selected="true"{/if}>Contacts</option>
<option value="enrollment" {if $cmdOn == "enrollment"}selected="true"{/if}>Enrollment</option>
<option value="all" {if $cmdOn == "all"}selected="true"{/if}>All Schools</option>
</select>
<input type="submit" name="doSwitch" value="Submit" />
</td>
<div id="append"></div2>
</form>
This is my HTML. My jQuery is:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php?cmd=str";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post( url, { cmdview: str } ,
function( data ) {
var content = $( data );
$('#append').load(url);
})
.change();
});
</script>
The problem is my $_GET value (cmd) is always "str". It won't take the value of my select HTML. I can't figure out the syntax for it to great the select value.
All I need is str to = the value of whatever < . option . > is selected
EDIT::
I'd like to add that I know the $.post isn't needed now that I'm doing a _GET value. But, I don't know how else to format this... :(
change
url = "maps_append.php?cmd=str";
to
url = "maps_append.php?cmd=" + str;
Make sure you have proper indentation, or else you are going to get lost quickly. I have cleaned up most of your code. You were hard coding "str" in your url instead of concatenating the variable:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = '',
url = 'maps_append.php?cmd=';
$('select option:selected').each(function () {
str += $(this).text() + ' ';
});
url += str;
$.post( url, { cmdview: str } , function( data ) {
var content = $( data );
$('#append').load(url);
}).change();
});
</script>
Also note that you are first doing a POST request to maps_append.php which will have both $_POST['cmdview'] and $_POST['cmd'] set to the options you sent, then once that script has returned a response, you make a GET request by using the load() method, which will then replace the HTML in #append. Not sure why there is that last change() at the end.
From what I can tell, it sounds more like you're trying to do something more like this:
<script>
$('#cmdview').change(function() {
var url = 'maps_append.php?cmd=' + $(this).val();
$.get(url, function(data){
$('#append').append(data);
});
});
</script>
I believe that what you're are trying to accomplish can be resolved with much simpler code. Try replacing your existing JavaScript with this:
$(function() {
$('#cmdview').change(function() {
$('#append').load("maps_append.php?cmd=" + $(this).val());
}).change();
});
This code is simply saying, when you change #cmdview load the contents of the file maps_append.php?cmd= with the value of #cmdview appended to the url. This should make it so you can access the value of #cmdview in your PHP code with $_GET['cmd'].
Related
I have a .php page with about two hundred select form elements on it. The element values are being populated by a .txt file in the same directory using PHP:
<?php
$schoolselected = 'schools.txt';
$eachlines1 = file($schoolselected, FILE_IGNORE_NEW_LINES);
?>
and
<select name="schoolselected001">
<option value="" disabled selected>Select School...</option>
<option value=" " <?php if(isset($_POST['schoolselected001'])) echo "selected"; ?>></option>
<?php foreach($eachlines1 as $lines1){
echo "<option value='".$lines1."'>$lines1</option>";
}?>
</select>
Each select form element have the same name but with 001 through 200.
I'm using this jQuery function to disable an option when selected to prevent doubling up:
<script>
$(document).ready(function(){
$('select[name*=schoolselected]').on('click', function() {
$('option').prop('disabled', false);
$('select[name*=schoolselected]').each(function() {
var val = this.value;
$('select[name*=schoolselected]').not(this).find('option').filter(function() {
return this.value === val;
}).prop('disabled', true);
});
}).change();
});
</script>
Everything works perfectly and there was no delay when I tested with ten values but now with two hundred values, there is a 10-12 second delay each time I click any of the select form elements.
Are there any tweaks I can do to the existing code to remove the delay? Or maybe I'm taking the wrong approach? I looked into caching the data but had no luck finding a solution. If I disable the jQuery function there is zero delay. Any help or suggestions would be appreciated.
So many questions to what you are trying to achieve
Why 200 select dropdowns?
Why did you use 'on click' on a select? you want 'on change' event right?
your code is slow because you are iterating twice over your 200 selects
here is the working code
<script>
$(document).ready(function(){
var lastSelectedValue = {};
$('select[name*=schoolselected]').on('change', function() {
var currentSelect = this.attributes.name.value;
var oldValue = lastSelectedValue[currentSelect];
lastSelectedValue[currentSelect] = this.value;
$('select[name*=schoolselected]').not(this).each(function() {
if(oldValue){
$(this).find("option[value='"+oldValue+"']").prop('disabled', false);
}
$(this).find("option[value='"+lastSelectedValue[currentSelect]+"']").prop('disabled', true);
});
});
});
</script>
I want to set selected value of a select input to a php variable. When I select a value from select box, then want to put that value in php variable and use echo select option value, but I can't get this value in select box inside php code. My Code is given below.
<body>
<select>
<?php
$test='<label id="output"></label>';
echo "<option>".$test."</option>";
?>
</select>
<select id="sel">
<option>--select--</option>
<option>amr</option>
<option>tomar</option>
</select>
</body>
<script type="text/javascript">
$(document).ready(function(){
$( "#sel" ).change(function() {
var ww = $( "#sel" ).val();
//alert(ww);
$( "#output" ).text(ww);
});
});
</script>
Use AJAX
$.ajax({
type: "POST",
url: "some.php",
data: { ww: ww}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
And in some.php using POST you can set $ww = $_POST['ww'];
Reference
http://api.jquery.com/jquery.ajax/
PHP is a server-side-language, so the php-code is executed before anything is showed on the screen.
That also means that when the page is loaded you can no longer interact with the php code.
For what it sounds like you're trying to do (a little hard to understand), it sounds like you need to use javascript to change the content on the page at runtime :)
You're select box hasn't got an id of sel, which is what the JS is listening for the change event on, I also can't see the div with the id output, which is where the results are going.<select id="sel"> And <div id="output"></div>
Is there a way to post both a select options value and it's content:
<option value="post this">post this too</option>
Not through HTML alone. You could do it with JQuery and some Ajax.
Example:
var optionValue = $("#yourSelectId").val();
var optionText = $("#yourSelectId option[value='" + optionValue + "']").text();
You can do it only with Javascript
JQUERY Example:
<form id="myform">
<select><option value="post this">post this too</option></select>
</form>
$("#myform").submit(function (){
$("#myform select option).each(function (element){
$(element).val($(element).val() + '||' + $(element).text());
});
});
For the content, you can post with PHP. For the value, I recommend this JavaScript:
function getValue()
{
var value = document.getElementById("optionid").value;
return value;
}
You can add a hidden input which will be populated with selected text from select control, for this you can use for example onchange event to which you will attach a javascript method.
I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here
I'm newbie with jQuery. I Want to get value from these two textarea,
I have html like this and jquery below :
Html :
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message">Hello</textarea>
<textarea id="message2" class="message">World</textarea>
</pre>
jQuery:
jQuery("a#send-thoughts").click(function() {
var thought= jQuery("textarea.message").val();
alert(thought);
});
Why only one value show up ? and how to get two value of textarea ?
http://jsfiddle.net/guruhkharisma/9zp9H/
var text = "";
jQuery("textarea.message").each(function(){
text += jQuery(this).val() + "\n";
})
Try thought = $('textarea').text()
i think this should work
or thought = $('.message').text();
Use the each() method.
jQuery("a#send-thoughts").click(function() {
jQuery("textarea.message").each(function() {
var thought= $(this).val();
alert(thought);
});
});
Check the online doc for more information: http://api.jquery.com/each/
.val(), like all the jQuery getters, returns the value of the first matched form-input element. You will have to use a .each() loop and concatenate the values:
jQuery("a#send-thoughts").click(function() {
var thought = '';
jQuery("textarea.message").each(function() {
thought += $(this).val() + ' ';
});
alert(thought);
});
<pre>
<a id="send-thoughts" href="">Click</a>
<textarea id="message1" class="message1">Hello</textarea>
<textarea id="message2" class="message2">World</textarea>
</pre>
jQuery:
jQuery("a#send-thoughts").click(function() {
var thought1= jQuery("textarea.message1").val();
alert(thought1);
var thought2= jQuery("textarea.message2").val();
alert(thought2);
});