I am having a problem with reading the data in checkboxes. I did some research on the net and found the below code. This code is for removing data with checkboxes though.
function deleteData()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
var sitepath = 'http://www.sinemalar.com/';
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert("Başarıyla silindi");
window.location.replace(window.location.pathname);
});
and this is the code which produces checkboxes.
{foreach value=artist2 from=$artist}
<br />
<input type="checkbox" name="artist[]" value="{$artist2.MOVIE_ID}-{$artist2.PERSON_ID}" { in_array array=$item match=$artist2.NAME_SURNAME returnvalue="CHECKED" }>{$artist2.NAME_SURNAME}<br />
<hr />
{/foreach}
The person who wrote this code uses this to read checkboxes. Do i have to use <p> to read my checkbox values or is there an alternative way?
.p16 input:checked
Do you mean:
$(document).ready(function() {
var checkedBoxesArr = [];
$("input[name='artist[]']").each(function() {
if($(this).is(":checked")) {
checkedBoxesArr.push($(this).val());
}
});
});
Related
Is it possible to do this in PHP + CSS? Got a textarea with the result of an array inside it:
<textarea class="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
The code below shows a textarea with something like this:
This is a beautiful line 1 from the array
This is a beautiful line 2 from the array
This is a more beautiful line 3 from the array
And so on.
So what I want is to add some text inside the textarea, then when click a submit button this text will be added to the array $scriptlauncher[]
If I wrote "this is my new text" then the result of textarea must be:
This is a beautiful line 1 from the array
This is a beautiful line 2 from the array
This is a more beautiful line 3 from the array
this is my new text
My first approach:
HTML and PHP and call to Javascript
<form name="frmscript" onsubmit="return false;">
<?php if (isset($_POST["script"])) {
$script = $_POST["script"];
}?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?>
</textarea><br><br>
<input type="button" name="execscript" value="Execute scripts" id="submit" onClick="addtext();" />
</form>
Javascript:
function addtext() {
var newtext = document.frmscript.ta_scripts.value;
document.frmscript.ta_scripts.value = "";
document.frmscript.ta_scripts.value += newtext;
window.location.href = "index.php?script=" + newtext;
}
Second Approach (can't save the new array yet)
HTML and PHP and call to Javascript:
<form name="frmscript" onsubmit="return false;">
<?php /*if (isset($_POST["script"])) {*/
if($_POST){
$script = json_decode($_POST["script"]);
}
?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
<input type="button" name="execscript" value="Execute scripts" id="submit" onClick="addtext();" />
</form>
Javascript:
function addtext() {
var script = document.frmscript.ta_scripts.value;
document.frmscript.ta_scripts.value = "";
document.frmscript.ta_scripts.value += script;
script = JSON.encode(script);
var miAjax = new Request({
url: "index4.php",
data: "script=" + script,
onSuccess: function(textResponse){
$('result').set("html", textResponse);
},
onFailure: function(){
$('result').set("html", "Error!!");
}
})
miAjax.send();
Third approach (Any help would be much appreciated!):
HTML and PHP:
<form name="frmscript" onsubmit="return false;">
<?php /*if (isset($_POST["script"])) {*/
if(isset($_GET['script'])){
$script = $_GET['script'];
}
?>
<textarea class="ta_scripts" name="ta_scripts"><?php
foreach ($script as $script_launcher){
echo $script_launcher."\r\n";
}?></textarea><br><br>
<input type="button" name="execscript" value="Exec script" id="submit" onClick="addtext();" />
</form>
Javascript:
$(document).ready(function () {
$('#execscript').click(function () {
/* var name_val = $('input[name="script"]').val();*/
var script = document.frmscript.ta_scripts.value;
$.ajax({
type: "GET",
url: "index4.php", //get response from this file
data: {
name: script
},
success: function (response) {
$("textarea#ta_scripts").val(response); //send response to textarea
}
});
});
});
I'm not sure I completely understand you, but in order to read lines into an array:
$text = trim($_POST['testtextarea']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
//Push to scriptlauncher array.
array_push($scriptlauncher, $line);
}
I've not tested this, but it should put you on the right track.
I want to filter realtime results with jQuery (just like on this site http://shop.www.hi.nl/hi/mcsmambo.p?M5NextUrl=RSRCH). So when someones checks a checkbox the results should update realtime (in a div). Now I'm a newbie with jQuery and I've tried lots of examples but I can't get it to work. Here's my code, could anyone tell what I'm doing wrong? Thank you very much!
HTML
<div id="c_b">
Kleur:<br />
<input type="checkbox" name="kleur[1]" value="Blauw"> Blauw <br />
<input type="checkbox" name="kleur[2]" value="Wit"> Wit <br />
<input type="checkbox" name="kleur[3]" value="Zwart"> Zwart <br />
<br />
Operating System:<br />
<input type="checkbox" name="os[1]" value="Android"> Android <br />
<input type="checkbox" name="os[2]" value="Apple iOS"> Apple iOS <br />
</div>
<div id="myResponse">Here should be the result</div>
jQuery
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
var dataString = $(allVals).serialize();
$.ajax({
type:'POST',
url:'/wp-content/themes/u-design/filteropties.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
}
$(document).ready(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
PHP
//Just to see if the var passing works
echo var_export($_POST);
You are using .serialize() incorrectly, it works only with form elements.
With this code i think you'll get what you need.
Javascript / JQuery
function updateTextArea() {
var allVals = "";
$('#c_b input[type=checkbox]:checked').each(function() {
currentName = $(this).attr("name");
currentVal = $(this).val();
allVals = allVals.concat( (allVals == "") ? currentName + "=" + currentVal : "&" + currentName + "=" + currentVal );
});
$.ajax({
type:'POST',
url:'/wp-content/themes/u-design/filteropties.php',
data: allVals,
dataType: "html",
success: function(data){
$('#myResponse').html(data);
}
});
}
$(document).ready(function() {
$('#c_b input[type=checkbox]').click(updateTextArea);
updateTextArea();
});
i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.
I have a little bit problem with reading datas from checkboxes.
{foreach value=artist2 from=$artist}
<br />
<input type="checkbox" name="artist[]" value="{$artist2.MOVIE_ID}-{$artist2.PERSON_ID}" { in_array array=$item match=$artist2.NAME_SURNAME returnvalue="CHECKED" }>{$artist2.NAME_SURNAME}<br />
<hr />
{/foreach}
<p align="right"> <a style="float: right" href='javascript:void(null);' onclick="deleteData();" ><input type="submit" name="removeArtistFromMovie" onclick="showMessage('Seçilen oyuncu(lar) başarıyla silindi')" value="Seçilenleri Sil" id="value"</p></a>
<br >
</form>
I produce checkboxes like that and in my js file:
I try this
function deleteData(){
var artistIds = new Array();
$("input[#type=artist[]][#checked]").each(function(){
artistIds.push($(this).attr('id'));
});
alert(artistIds);
$.post('/management/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert("Başarıyla silindi");
window.location.replace(window.location.pathname);
});
}
However, above code does not take the values of checkboxes which is checked. Why ?
Finally
I think problem is here because the page does not go to js.
<form name=form1 method=post action=# onsubmit='return validate(this)'>
<br />
<input type="checkbox" name="artist[]" value="{$artist2.MOVIE_ID}-{$artist2.PERSON_ID}" />{$artist2.NAME_SURNAME}<br />
<hr />
{/foreach}
<p align="right">
<a style="float: right" href='javascript:void(null);' onclick="deleteData();" ><br />
<input type="button" name="checkArtistButton" value="Seçilenleri Sil" id="ajaxCheckbox" /></a></p>
<br >
</form>
and this is my js
function deleteData(){
var artistIds = [];
$('#ajaxCheckbox').click(function() {
$("input[name='artist[]']:checked").each(function() {
artistIds.push($(this).attr('value'));
});
alert(artistIds);
});
$.post('/management/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert("Başarıyla silindi");
window.location.replace(window.location.pathname);
});
}
instead of
$("input[#type=artist[]][#checked]").each(function(){
try
$("input[name='artist[]']:checked").each(function(){
Working example here
note
I think you mean to get the value of the checkboxes - as looking at your markup they do not have id attributes - use .val() instead of attr('id') to get the value
Update
You are now setting up an event handler on the click of an anchor ... change this
function deleteData() {
var artistIds = [];
$('#ajaxCheckbox').click(function () {
$("input[name='artist[]']:checked").each(function () {
artistIds.push($(this).attr('value'));
});
alert(artistIds);
});
to this
function deleteData() {
var artistIds = [];
$("input[name='artist[]']:checked").each(function () {
artistIds.push($(this).val());
});
alert(artistIds);
the deleteData function is already called onclick
Use the :checked selector instead of [#checked] (btw, you do not use # in CSS property selectors). You also used the wrong property selector for the name. I've also simplified your code a bit; your use-case is perfect to use .map(..).get()
var artistIDs = $("input[name='artist[]']:checked").map(function(){
return this.id;
}).get();
Demo: http://jsfiddle.net/ThiefMaster/sBmdC/
Try below line of code:
var artistIds = Array();
$("input[name=artist[]]:checked").each(function(index){
artistIds[index] = $(this).val();
});
This may work for you..
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;