javascript subscribe form change - javascript

I have this code for form output, but I want to change the result so that it will load two buttons which will subscribe and unsubscribe, how do I do that?
Tried
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val(1) + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;">Subscribe</span></a></div>
and
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val(0) + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;">Unsubscribe</span></a></div>
But no effect
<div class="box">
<!-- <div class="box-heading"><?php echo $heading_title; ?></div> -->
<h3><?php echo $heading_title; ?></h3>
<div class="box-content">
<div id="newsletter_message" class="content" style="display:none; background: #FFFFCC; border: 1px solid #FFCC33; padding: 10px; margin-top: 2px; margin-bottom: 15px;"></div>
<form action="<?php echo $action; ?>" method="post" id="module_newsletter" name="module_newsletter">
<div style="text-align: left;">
<span class="required">*</span><b><?php echo $entry_email; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_email" required placeholder="<?php echo $entry_email; ?>"/><br />
<?php if ($name == 'optional') { ?>
<b><?php echo $entry_name; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_name" placeholder="<?php echo $entry_name; ?>"/>
<?php } elseif ($name == 'required') { ?>
<span class="required">*</span><b><?php echo $entry_name; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_name" placeholder="<?php echo $entry_name; ?>"/>
<?php } else { ?>
<input type="hidden" name="name" value="" />
<?php } ?>
<br />
<input name="subscribe" value="1" type="hidden" />
</div>
<table style="align:left;">
<tr>
<td style="width: 100%;">
<table>
<tr>
<td><input type="radio" style="vertical-align: middle;" id="subscribe" name="subscribe" value="1" checked="checked"/><label style="font-size:10px; vertical-align: middle;" for="subscribe"><?php echo $text_subscribe; ?></label></td>
</tr>
<tr>
<td><input type="radio" style="vertical-align: middle;" id="unsubscribe" name="subscribe" value="0" /><label style="font-size:10px; vertical-align: middle;" for="unsubscribe"><?php echo $text_unsubscribe; ?></label></td>
</tr>
</table>
</td>
<td></td>
</tr>
</table>
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val() + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;"><?php echo $button_go; ?></span></a></div>
</form>
</div>
</div>

Replace this...
$('input[name=\'subscribe\']:checked').val()
With this...
$('input[name=subscribe]:radio:checked').val()
You need the :radio selector as you also have a hidden form input with the same name. Bear in mind what this fact may do to your form for non-javascript users.

As requested, here is a more thorough answer. I can't help you fix all your code, as that is outside of the scope of Stack Overflow, however here is something to help you get started.
Basic working example: http://jsfiddle.net/jeb2x/
Let's say you have a form...
<form id="SubscribeForm">
<input type="radio" name="subscribe" value="1" checked="checked" />
<input type="radio" name="subscribe" value="0" />
Alert selected value
</form>
You can subscribe to the click event of the link with id alert and have it alert the selected radio button value. This Javascript code should be in a separate file to your html, and included in the head using a script tag.
<script type="text/javascript" src="/pathtofile/scripts.js"></script>
...
$(document).ready(function(){
$('#SubscribeForm').on('click', 'a#alert', function(){
var selectedValue = $('input[name=subscribe]:checked').val();
alert(selectedValue);
});
});
There are a few principles you need to learn about in order to understand the code here.
Firstly, it is subscribing to the ready event of the document. This ensures that the code only runs when the DOM has finished loading, and therefore, your form is definitely ready to be used. There is also a shorthand way of subscribing to document ready, which is to pass an anonymous function to jQuery, and it knows to run it on DOM ready
$(function(){
//...code here
});
It is then subscribing to the click event of the form. This code uses a principle called event delegation, which is worth reading up on. It's not really needed for this simple example, but is advantageous if you need to bind to multiple events within the same div for example. The code could in this case be simplified to...
$('a#alert').on('click', function(){
var selectedValue = $('input[name=subscribe]:checked').val();
alert(selectedValue);
});
...or even just $('a#alert').click(function(){
The code then uses my original solution (minus the :radio selector, which isn't needed as there is only one group of inputs with the name 'subscribe'), to alert the selected value.
In your case, you are trying to call an external script in order to subscribe or unsubscribe users. One way to do this is to use an AJAX request. You could use any of a number of methods to do this. You are using the load method above, which will send a request to the url supplied, and insert the response into the selected element.
$("#result").load( "test.html" );
In the example here, the response from test.html will be inserted into the element with id result. If you wanted to do something more complex with the response, you could use one of jQuery's AJAX methods, such as $.ajax() or $.get()
Hope this helps :)

Related

how to write HTML tags with jQuery n json dynamically?

I need to write html code into the following div with jquery
<div id="addme"></div>
following is my html with php
<div class="col-md-4 product secondproduct">
<div class="images1">
<a
href=" <?php echo base_url();?>products/details/<?php echo $product->productid?>">
<img
src="<?php echo base_url();?>assets/images/products/<?php echo $product->productimage;?>" />
</a>
</div>
<div class="title1">
<?php echo $product->productname;?>
</div>
<div class="price1">
Rs. <?php echo $product->productprice;?>
</div>
<div class="productadd">
<form method="post" action="<?php echo base_url();?>cart/productadd">
<div class="qtyout">
QTY : <input type="text" class="qty" name="qty" value="1" />
</div>
<input type="hidden" name="item_number"
value="<?php echo $product->productid;?>" /> <input
type="hidden" name="price"
value="<?php echo $product->productprice;?>" /> <input type="hidden"
name="title" value="<?php echo $product->productname;?>" />
<button class="btn btn-primary btn-lg" type="submit">Add To Cart</button>
</form>
</div>
</div>
actually i want to populate these html & php with json & query. And kinda getting lots of error. main problem is, i don't know how to write these about of html tags inside jquery and loop through json data.
Thanks in advance
to add something in the addme div you do
$("#addme").html('insert content here');
or you can append something(keeps whats there and add stuff to the end):
$("#addme").append('insert content here');
for the json. Once you have a json string you do
var yourdata = JSON.parse(jsonstring)
Hope this helps a bit
Do Something like following:
var obj = $.parseJSON({"productid":"2","categoryid":"1","manufacturerid":"2","name":"Abraham Lincoln Printed T-Shirt","price":"1250.00","color":"red","description":"Print Name: Abraham Lincoln\r\n100% Cotton\r\nMade in Nepal\r\nRegular fit\r\nHalf sleeve","quantity":"20","otherdetails":"Available in all sizes.","isadvertised":"1","isnew":"1","image":"hazy-crazy-t-shirt.jpg","manuid"‌​:"2"}');
$(".image1").html(obj.image);
$(".color1").html(obj.color);
If you are getting data in json by ajax than you can simply append in html with the specific div, follow the code below:
Using ajax return :
var myAjaxreturn = "Your code which is to append";
<div id='addme'></div>
$('#addme').html(myAjaxreturn);
Jquery append() inserts content, specified by the parameter, to the end of each element in the set of matched elements.
var response = "your ajax response";
$( "#addme" ).append( response );
OR
$( "#addme" ).html( response );
Hope this helps. not tested

Passing variable from within while loop to popupdiv

I have table which displays the values of SQL table. In each row there is a dropdown which allows you to select which action you want to do. When you select the action and click '
go', it pops up a form which I want to be able to pass the $id variable from the table to the popup div form, then on to the next pop page. ID displays correctly in dropdown, but whenever when it shows the div, its showing the incorrect id (its displaying the first id of the table, rather than the id of the selected dropdown).
Heres the php
while($row = mysql_fetch_array($proposal_result)) {
$date=substr($row["date"], 0, 50);
$formatted_date=date('d/m/Y', strtotime($date));
$id=substr($row["idproposal"], 0, 50);
$businessname=substr($row["businessname"], 0, 50);
$status=substr($row["status"], 0, 50);
$staff=substr($row["staff"], 0, 50);
$file_access='<bucket-location>';
$file_name='proposal_'.$id.'_'.$businessname.'.pdf';
$file=$file_access.$file_name;
print "<tr><td>".$formatted_date."</<td>
<td>".$id."</td>
<td width='25px'><a href='".$file."'target='_blank'><img src='".$images."/attachment.png' alt='file'></a></td>
<td>".$businessname."</td><td>".$staff."</td>
<td>".$status."</td>
<td>
<div>
<select id='zb-admin-dropdown' name='zb-admin-dropdown' class='dropdowns' required>
<option value='0'>Select and action...*</option>
<option value='1'>Change Status for ID#".$id."</option>
<option value='2'>Delete Proposal</option>
</select>
<input type='submit' id='report-submit' value='Go' onclick='displayDiv()'></div>
</td></tr>";
}
Javascript
function displayDiv() {
e=document.getElementById("zb-admin-dropdown");
strUser=e.options[e.selectedIndex].value;
if (strUser=='1') {
document.getElementById('abc').style.display = "block";
}
if (strUser=='2') {
document.getElementById('def').style.display = "block";
}
}
popupdiv
print "<div id='abc'>
<div id='popup'>
<form name='changestatus' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Change Status for ".$id."</h2>
<hr>
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='/delete?id=".$id."&businessname=".$businessname."'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>";
print "<div id='def'>
<div id='popup'>
<form name='deletefeedback' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Reason for deleting proposal <br />".$id."</h2>
<hr>
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Added by mistake<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>No longer required<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Incorrect Information Provided<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Reason 4<br />
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='/delete?id=".$id."&businessname=".$businessname."'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>";
My aim is pretty much to pass the correct ID to the popupdiv. Any help would be appreciated. You can ignore the content of the popupdiv forms.
In your html, you call the function when a button is clicked. Pass the variable there in the function call. So:
<input type='submit' id='report-submit' value='Go' onclick='displayDiv(' + $id + ')'></div>
Then have the javascript function accept an input:
function displayDiv(divId) { ...
and use it in the javascript. But the thing is, php is server side, and javascript is client side. So to get the information to the server-side php, you need to make an http request.
I can't see where all the code is but you may be able to try a couple work-arounds with minimal refactoring. First, after the div element is displayed, you can have the javascript update the href tag with:
`document.getElementById(/*a_element's_id*/).href=''+divId`
Otherwise, I'm not a php expert, but I think perhaps if the php scripts are in the same scope, a global variable or perhaps a global static variable would be accessible to both php scripts?
Personally I'd go all javscript! :)
Best of luck

AJAX post variables to current page via href onclick - Jquery Mobile/PHP

I am creating an application that utilizes JQuery Mobile and PHP, nothing crazy here. I am trying to update a $_POST[''] variable on the page I am currently viewing.
The user clicks on an "Issue_Title" to add "Issue_Txt" to that particular list. So I need a way to know which issue_title the user clicks on so I can add it to the right place. To solve that when I retrieve the issue_title from mySQL table I format like so (testTitle is just a placeholder for debugging...I want $row['issue_title'] there so I can distinguish which title was clicked):
echo "<li data-role='fieldcontain'>"."".$row['issue_title']."</li>";
So onclick it will run the below JS function:
function NewIssueTxt(issue_title)
{
var combined = {'issue_title' : issue_title};
combined = $('#HiddenIssueTxtForm').serialize() + '&' + $.param(combined);
$.ajax({type:'POST', url: 'NewRoundDetails.php', data: combined, success: function(response){ }});
return false;
};
I can see via Javascript Console that this is POSTing as expected when I click the listview link. This should give me a $_POST['issue_title'] that I can use to submit along with the issue_txt which is all captured in the below form...which is a popup form that also appears when the user clicks the Issue_Title href.
<div data-role="popup" id="popupNewIssueTxt" data-history='false' data-theme="a" class="ui-corner-all">
<form id="NewIssueTxtForm" action="/NewRoundDetails.php" onsubmit="return submit_popupNewIssueTxt();" method="post">
<div style="padding:10px 20px;">
<h3>Issue Text:</h3>
<label for="issue_txt" class="ui-hidden-accessible">Issue Text:</label>
<input type="text" name="issue_txt" id="issue_txt" value="" />
<label for="issue_title" class="ui-hidden-accessible">Issue Title</label>
<input type="hidden" name="issue_title" id="issue_title" value="<?php echo $_POST['issue_title']; ?>"/>
<label for="date" class="ui-hidden-accessible">Date:</label>
<input type="hidden" name="date" id="date" value="<?php echo $_POST['date']; ?>"/>
<label for="dept_name" class="ui-hidden-accessible">Department Name:</label>
<input type="hidden" name="dept_name" id="dept_name" value="<?php echo $_POST['dept_name']; ?>"/>
<label for="participants" class="ui-hidden-accessible">Participants:</label>
<input type="hidden" name="participants" id="participants" value="<?php echo $_POST['participants']; ?>"/>
<label for="issue_category" class="ui-hidden-accessible">Issue Category:</label>
<input type="hidden" name="issue_category" id="issue_category" value="Work Environment"/>
<button id="NewIssueTxtButton" form="NewIssueTxtForm" type="submit" data-theme="b">Add</button>
</div>
</form>
As mentioned I confirmed the JS function is working...except I still have no value for $_POST['issue_title']. What am I doing wrong? Is the JS function not submitted fast enough...so I click the Issue_title but my form is opened before the POST happens? If that's the case how else can I get the href clicked into a usable variable?
To reiterate: I'm populating a listview with data from a mySQL DB. I need a way of knowing which link or listview is clicked so I can POST it along with other form data.

Farbtastic Multiple Fields - Wordpress

I am developing a wordpress theme. I am working on the theme options page right now. I added farbtastic (4 fields) and the problem is that every time I click on the input, the color picker appears on the other 3 fields too. Anybody knows how to fix this? Thank you!
<div> <br />
<label for="<?php echo $colorPicker['ID']; ?>"><?php _e($colorPicker['label']); ?></label>
<input type="text" class="color-picker" id="<?php echo $colorPicker['ID']; ?>" value="<?php echo get_option($colorPicker['ID']); ?>" name="<?php echo $colorPicker['ID']; ?>" />
<div id="<?php echo $colorPicker['ID']; ?>_color" class="fabox"></div> </div>
<?php endforeach; ?>
<p><input type="submit" name="update_options" value="Update Options" class="button-primary" /></p>
</form>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
var colorPickers = $('.color-picker');
console.log(colorPickers);
for (e in colorPickers) {
if (colorPickers[e].id != undefined) {
var colorPickerID = colorPickers[e].id;
$('#' + colorPickerID + '_color').farbtastic('#' + colorPickerID);
}
}
$('.fabox').hide();
$('.color-picker').click(function() {
$('.fabox').fadeIn();
});
$(document).mousedown(function() {
$('.fabox').each(function() {
var display = $(this).css('display');
if (display == 'block') $(this).fadeOut();
});
});
});​
</script>
HTML OUTPUT:
<form method="POST" action="">
<div>
<br />
<label for="color_1"><strong>Post Title</strong></label>
<input type="text" class="color-picker" id="color_1" value="#273990" name="color_1" />
<div id="color_1_color" class="fabox"></div>
</div>
<div>
<br />
<label for="color_2"><strong>Paragraph Text</strong></label>
<input type="text" class="color-picker" id="color_2" value="#840000" name="color_2" />
<div id="color_2_color" class="fabox"></div>
</div>
<div>
<br />
<label for="color_3"><strong>Example</strong></label>
<input type="text" class="color-picker" id="color_3" value="#4377df" name="color_3" />
<div id="color_3_color" class="fabox"></div>
</div>
<div>
<br />
<label for="color_4"><strong>And Another Example</strong></label>
<input type="text" class="color-picker" id="color_4" value="#3c8400" name="color_4" />
<div id="color_4_color" class="fabox"></div>
</div>
<p><input type="submit" name="update_options" value="Update Options" class="button-primary" /></p>
</form>
</div>
You're referencing too broad of an element with your jQuery selector. Essentially your code says every time you click anything with the color-picker class, show anything with the fabox class.
You should make your reference more specific to the currently clicked .color-picker.
I recommend replacing this:
$('.fabox').fadeIn();
With this:
$(this).parent().find('.fabox').fadeIn();
So you are only referencing the .fabox that is connected to the .color-picker you just clicked.
EDIT: As gillesc noted, it would actually be quicker to use:
$(this).next().fadeIn();
So long as the the .fabox always follows the .color-picker.
If the .fabox was inside the same container, but not the very next element you could use:
$(this).next('.fabox').fadeIn();
You don't need to use for (e in foo) using jQuery.each(), is a lot cleaner and here your e is a global variable which is pretty bad, with each that mistake can't happen.
Also use $(function(){}); instead of $(document).ready(function(){}); it does exactly the same but you get better footprint and your code is a bit easier to read.
And in the dom ready function you don't need $ as argument, that when you need a closure and is a way to guarantee $ is jQuery inside the closure.
(function($) {
// your code
})(jQuery);
So your code end up like this instead of what you have
$(function() {
$('.color-picker').each(function() {
if (this.id) {
$('#' + this.id + '_color').farbtastic('#' + this.id);
};
}).click(function() {
$(this).next().fadeIn();
});
$('.fabox').hide();
$(document).mousedown(function() {
$('.fabox:visible').fadeOut();
});
});​
And I think your problem might be idtencial IDs so it confuse the plugin, but to be fair it would easier if you post the HTML output rather than the PHP code as it's the DOM we want to see and it's hard to guess without knowing what the PHP variables are outputting.

Conflict between 2 scripts in jquery

I'm trying to use an input validation script in jquery. Which executes on document ready event.
$(function(){
$("#cart").validationEngine();
});
Here's the form where I want to use it:
<form id="cart" name="cart_form">
<?php foreach($product as $prods): ?>
<tr>
<td><input type="text" id="qty_sel<?php echo $prods['PID']; ?>" name="qtysell[]" class="validate[required]"/></td>
<td><input type="text" name="subtotal" id="subtotal<?php echo $prods['PID']; ?>" class="validate[required]" readonly="readonly"/></td>
<?php endforeach; ?>
</form>
The above code doesn't work, but when I tried it in something simpler, it actually worked:
<form id="cart" name="a">
<input type="text" id="name" class="validate[required]"/>
</form>
Does this have something to do with another script which I have written which computes the subtotal from the given price and quantity.
Or is it the ordering of the elements (table, form, input). Which causes the script to not work.
if you have some custom handler on the form's submit action such as
document.getElementById("formID").onsubmit = function(){
//custom code here
}
Then the validationEngine will not work ...
Try adding your function to validationEngine.js

Categories

Resources