Javascript - Get Multiple textarea values with jquery - php

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);
});​

Related

how to pass java script value to php in codeigniter

i have a form where two fields are dynamically generated through java script when a button is clicked.when the button is clicked each time,the two text field will generate again and again.now i have got the count of text field generated in a hidden field in JavaScript.How can i get the value of hiddenfield in controller and insert the values of text fields in database,by appending comma in data when the text box value is entered each time.please help me.
my javascript is
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
}
</script>
my html code is
<input type="button" id="button1" onclick=getField();/>
<div id="renderDiv">
</div>
inside this div the two textfield is generated along with the hidden field
i am not getting the value of textfield in controller while submitting and i am not getting the count of textfield.i tried like $hiddenfield=$this->input->post('hiddentextField');
you will have to post the variable inorder to pass this to the server
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
window.location.href = "index.php?name=" + countbox-1;
//change index.php to your page name
}
</script>
then in the same page
<?php
$hiddenfield=$_GET["name"];
?>
I had the same problem before, what I did is I insert those text box inside a table, lets say, tableSample
then I use jQuery find
var _content = '';
var _findcontent = $("#tableSample");
_findcontent.find("tr").each(function(){
$(this).find("td").each(function(){
$(this).find("input").each(function(){
_content += $(this).val+'~'+$(this).attr("id")+'|';
});
});
});
Then use ajax to pass it to your PHP
$.post("<?php echo site_url('controller_name/method_name'); ?>",
{
content : _content
}
,function( _data){
jAlert("alert",_data,"alert");
});
In your PHP, you can use explode to get the desired values,
$content_from_page = $this->input->post("content");
$explode_string = array();
$explode_string = explode("|",$content_from_page );
$explode_arr = array()
for($x=0;$x<count($explode_string)-1;$x++)
{
$explode_arr[] = explode("~",$explode_string[$x];
}
then print_r($explode_arr); to check
*Note: The only problem with this approach is that, if the character that is inserted into the textbox is ~ or |, coz that is the delimiter used.

Select - post values?

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.

How to get index of input in javascript - can use jQuery

I have an array of inputs generated from js code. I have set the name of the inputs like this: name="myTextInput[]"
How can I get the index of the selected input?
I tried something like:
onClick="oc(this);"
where:
function oc(inp)
{
return(inp.index);
}
but is not working.
I can use jQuery as well
You can use the EACH function in jquery. This will parse through the set of matched elements. You can put a custom function inside that will use the index of each element, as you parse through, as an argument.
$('input').each(function(index){
alert(index);
});
You can also get the value of each input like this:
$('input').each(function(index, val){
alert(index + ' has value: ' + val);
});
see details here: http://api.jquery.com/jQuery.each/
** EDIT **
If you want the value shown in an alert box on click, use the each function and the click function together. Remember to get the real-time value of the input, use $(this).val(). Return index and value data on click:
$('input').each(function(index, val){
$(this).click(function(){
alert(index + ' has value: ' + $(this).val());
});
});
You could get the input like this (not sure if you actually wanted the click event though)...
var inputs = $('input[name="myTextInput[]"]');
inputs.click(function() {
alert(inputs.index(this));
});
Please use the index() method to find the position of an element.
Check out this example: http://jsbin.com/uyucuv/edit#javascript,html
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
$(function() {
$("li").on("click", function() {
alert($(this).index());
});
});
Check the index() documentation here: http://api.jquery.com/index/
Hope this helps!
The "jQuery way" is to avoid onClick="whatever()" and use pure JavaScript separate from the HTML tags. Try this between a pair of <script> tags (note: requires jQuery 1.7 or higher):
$('input').on('click', function() {
var varname = $(this).attr('name'),
$arr = $('input[name="'+varname+'"]'),
idx = $arr.index(this);
alert(idx);
});​
http://jsfiddle.net/mblase75/EK4xC/

jQuery add form select value to $_GET value of remote file

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'].

How to get the textarea ID using jQuery

Ive got textarea area on each table row with unique ID .
How to retrieve that unique id with javascript?
PHP:
$query = $db->query("SELECT * FROM bs_events WHERE eventDate = '".$date."'");
while($row = $query->fetch_array(MYSQLI_ASSOC)){
echo '<textarea id=\"att_name_" . $row['id'] . "\" style=\"width:300px\"></textarea>";'
}
PHP OUTPUT:
<textarea id="att_name_1" style="width:300px">
<textarea id="att_name_2" style="width:300px">
<textarea id="att_name_3" style="width:300px">
jQuery:
$(document).ready(function(){
$("#book_event").submit(function(){
id = event.target.id.replace('att_name_','');
$.post("Scripts/book_event.php", {
att_name: $("att_name_"+id).val(),
}, function(data){
if(data.success) {
$("#err").text(data.message).fadeIn("slow");
}
}, "json");
});
});
It looks to me like you're naming your textareas to correlate to the database entries, then trying to make updates and pass those values back. Assuming the textareas are in the form you're submitting, you can use:
$('#myform').submit(function(e){
// find each of those text areas
$(this).find('textarea[id^=att_name]').each(function(i,e){
//
// from here-in, e now represents one of those textareas
//
// now submit the update
$.post('Scripts/book_event.php',{
att_name: $(e).val()
},function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
},'json');
});
e.preventDefault();
});
Ideally though, if you're looking to use AJAX to push updates/changes back to the server, you may look in to .serialize() and push all forms back. Then, on the server-side you'll get the standard $_POST['att_name_1'] values that you can use for your actual updating. e.g.
// .serialize() example
$('#myform').submit(function(e){
$.post('Scripts/book_event.php',$(this).serialize(),function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
});
e.preventDefault();
});
To solve your problem, you can use each()
$(function()
{
$("textarea").each(function()
{
var textarea_id = $(this).attr('id');
});
});
I don't fully understand the question.
If you want a list of the ids, how about something like:
$(document).ready( function ( ) {
var textareas = new Array();
// Run through each textbox and add the id to an array
$("textarea").each( function( ) {
textareas.push( $(this).attr("id") );
});
// Print out each id in the array
textareas.forEach( function(i) { alert(i); });
});
(that's untested and probably not the quickest way - I'm a bit out of practice)

Categories