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..
Related
I wrote below code using while loop printed like below
<p>
<input id="txtBox<?php echo $a; ?>" type="text" value="1" style="display:none;" />
<span id="txtBoxValue<?php echo $a; ?>">1</span>
</p>
when I click or select on the span I need convert it to the text field and after when deselect it will return to span text again
for this task, I wrote multiple jquery functions but I need it to be a single function is it possible?
thankyou in advance
<script>
$(function() {
$('#txtBoxValue1').on('click', function() {
$(this).hide();
$('#txtBox1').show();
});
$('#txtBox1').on('blur', function() {
var that = $(this);
$('#txtBoxValue1').text(that.val()).show();
that.hide();
});
$('#txtBoxValue2').on('click', function() {
$(this).hide();
$('#txtBox2').show();
});
$('#txtBox2').on('blur', function() {
var that = $(this);
$('#txtBoxValue2').text(that.val()).show();
that.hide();
});
});
</script>
Try to make it dynamic. use class="textboxevent" data-id="<?php echo $a; ?>"
<p>
<input class="textboxevent" id="txtBox<?php echo $a; ?>" data-id="<?php echo $a; ?>" type="text" value="1" style="display:none;" />
<span class="txtBoxValue<?php echo $a; ?>">1</span>
</p>
$(function() {
$('.textboxevent').on('click', function() {
var id = $(this).data('id');
$('#txtBox' + id).show();
});
$('.textboxevent').on('blur', function() {
var that = $(this);
var id = $(this).data('id');
$('#txtBoxValue' + id).text(that.val()).show();
that.hide();
});
});
Incremental id attributes are an anti-pattern, mostly because they lead to needlessly verbose JS logic.
A better solution is to use common classes on element with the same behaviour and then use DOM traversal to relate the elements to those around them. Try this:
jQuery(function($) {
$('.txtBoxValue').on('click', function() {
$(this).hide().prev('input.txtBox').show();
});
$('.txtBox').on('blur', function() {
var $that = $(this).hide();
$that.next('.txtBoxValue').text($that.val()).show();
});
});
.txtBox {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<input class="txtBox" type="text" value="1" />
<span class="txtBoxValue">1</span>
</p>
<p>
<input class="txtBox" type="text" value="2" />
<span class="txtBoxValue">2</span>
</p>
<p>
<input class="txtBox" type="text" value="3" />
<span class="txtBoxValue">3</span>
</p>
I have a form for Tags that is working OK, with some server validation, I would like to add a Jquery to submit the content without refreshing:
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input type="submit" value="Add" name="add" />
</div>
</form>
Any advice will be highly appreciated.
Check out the jQuery Form Plugin. Using it, you can submit a form without reloading the page like so:
<form id="aForm" action="target.php" method="post>
...
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#aForm").ajaxForm();
});
</script>
The ajaxForm() function also supports all options (such as a callback function) that can be passed to the standard jQuery $.ajax function.
$(document).ready(function() {
$(form).submit( function() { // could use $(#submit).on('click', function(){ as well
$.ajax({
url: 'yourposturl',
data: $(form).serialize(),
Success: function() {
alert('ok');
}
}); //end ajax
return false;
}); //end submit()
});
Should take all form vars , serialize them so the server can receive, the return false is so page doesnt refresh on submit (stops propagation and default)
Add the JQuery javascript library
Turn the submit into a button
<button id="submitbutton" >Add</button>
Add ids to your inputs
<input type="text" id="tag" name="tag" />
And add the jquery to the click for the button ...
<script type="text/javascript">
$(document).ready(function() {
$("#submitbutton").button().click(function(){
$.post("tags.php",{id: $("#id").val(), tag: $("#tag").val()});
});
});
</script>
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input class="button" type="button" value="Add" name="add" />
</div>
</form>
$(function(){
$('.button').click(function(){
var data = $('form').serializeToObject();
$.post('tags.php', data);
});
});
// jQuery Extension to serialize a selector's elements to an object
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
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 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());
}
});
});
I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}