jquery target input value inside divs with class checked - php

I am foreaching a number of suppliers in a quotation form, each with a checkbox element to tick which should be contacted. suppliers are in divs with class names supplier-checkbox, moreover upon selecting supplier the supplier-checkbox div gets appended with "checkedsupplier" or "uncheckedsupplier" class name.
<div class="supplier-checkbox checkedsupplier">
<input type="hidden" name="supplier-email" class="supplieremail" value="{$item->email}" />
</div> <!--end supplier checkbox-->
foreach supplier div I get a hidden input field within the div holding the supplier email as its value. idea is that upon submitting form I'd check for all div's with "checkedsupplier" class name and for each obtain the value of the input inside of it, hold all values in onelong variable and echo it into the To field of the email to replicate the quotation form to each supplier.
using jquery, I managed to toggle the class name and a background effect showing ticked or unticked with the below.
<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
});
</script>
can anyone give me any pointers on how to foreach by class name and fetch value of each input inside every div with that class name using jquery. Im working on it and yet found the .each for looping .val for values and if (bar) for conditional. but am not yet experienced enough to put things together. have been working as a junior developer for 7 months now since graduating in networking which is a completely different field.
in the app.js file I'm obtaining the form values this way:
`
v_country:$('#country').val(),
v_quotationtel:$('#quotationtel').val(),
v_mobile:$('#mobile').val(),
v_quotationemail:$('#quotationemail').val(),
v_quotemefor:$('#quotemefor').val(),
v_quotemessage:$('#quotemessage').val()
//this line is what i'm trying to do to get input values and store them in one var to pass them to php form that sends email $( "checksupplier" ).each(function( i ) {
}`
thanks everyone on stack! I believe in you guys here you've all helped me throughout my studies and work.
Ian
** Update ** It's been modified to work as follows:
<script>
$(function(){
$( ".crew-member-con" ).click(function(){
$(this).toggleClass('whitebg greybg');
$(this).toggleClass('crew-checked crew-unchecked');
$(this).toggleClass('grey white');
if($(this).children('input').prop('checked') == true){
$(this).children('input').prop('checked', false);
}else{
$(this).children('input').prop('checked', true);
}
var selectedMembers='';
$('.selected-members').each(function(){
if($(this).is(':checked')){
selectedMembers +=$(this).val()+', ';
}
//alert(emails);
});
if(selectedMembers != ''){
selectedMembers = selectedMembers.slice(0,-2);
}
$('#exam-member span').html(selectedMembers);
console.log(selectedMembers);
});
});

Here's an example with some notes.
$('.myform').submit(function () {
getEmailAddresses();
return false;
}
function getEmailAddresses () {
// a place to hold them
var emails = new Array();
// what will be after 'mailto'
var emailsString = "";
// get 'em
$('.checkedsupplier').each(function () {
// get the hidden email input value
var email = $(this).find('.supplieremail').val();
// check, just in case;
if (email) {
// push the value into our array
emails.push(email);
}
});
//put them all together into a string, split by a semi-colon
emailsString = emails.join(';');
// finally, stuff our mail to link.
// Not sure what you're plan is here but 'emailsString' has all of the values you eed.
$('.mailtolink').attr('href', 'mailto:'+emailsString);
}

<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
var emails='';
$('.supplieremail').each(function(){
emails +=$(this).val();
});
$('#mailfieldstextarea').val(emails);
});
</script>
I hope this will help.

Related

Submit jQuery multiple date picker form as POST data

I love this jQuery datepicker that I want to implement on a PHP form with other input boxes
http://multidatespickr.sourceforge.net/
When the user hits a submit button they are brought to another page update.php where the form data is obtained via POST.
I'm looking for a line to add to the javascript so I can somehow access the array of multiple dates in the multiple datepicker via POST:
var latestMDPver = $.ui.multiDatesPicker.version;
var lastMDPupdate = '2012-03-28';
var dates = $('#simpliest-usage').multiDatesPicker('getDates');
// Version //
//$('title').append(' v' + latestMDPver);
$('.mdp-version').text('v' + latestMDPver);
$('#mdp-title').attr('title', 'last update: ' + lastMDPupdate);
// Documentation //
$('i:contains(type)').attr('title', '[Optional] accepted values are: "allowed" [default]; "disabled".');
$('i:contains(format)').attr('title', '[Optional] accepted values are: "string" [default]; "object".');
$('#how-to h4').each(function () {
var a = $(this).closest('li').attr('id');
$(this).wrap('<'+'a href="#'+a+'"></'+'a>');
});
$('#demos .demo').each(function () {
var id = $(this).find('.box').attr('id') + '-demo';
$(this).attr('id', id)
.find('h3').wrapInner('<'+'a href="#'+id+'"></'+'a>');
});
// Run Demos
$('.demo .code').each(function() {
eval($(this).attr('title','NEW: edit this code and test it!').text());
this.contentEditable = true;
}).focus(function() {
if(!$(this).next().hasClass('test'))
$(this)
.after('<button class="test">test</button>')
.next('.test').click(function() {
$(this).closest('.demo').find('.box').removeClass('hasDatepicker').empty();
eval($(this).prev().text());
$(this).remove();
});
});
});
Looking at the plugin you can store the range as a common seperated list in a regular input field. Use jquery to disable to field from direct entry so people can't "mess it up" then after you post you an implode the field on a comma and then you will have your array.
http://multidatespickr.sourceforge.net/#undefined-demo
I'm not sure if that's what you're looking for, but if you need to access the dates passed to the script via POST just do this:
$dates = explode(',', $_POST['simpliest-usage']);

Grab checkbox values before form submission

I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.

Pass multiple values to jQuery

I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.
The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.
If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});

Passing a variable from within a while loop to a jquery

I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );

jQuery get values from selected checkboxes

First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.

Categories