HTML onclick function doesn't work - javascript

I am wondering why my onclick function doesn't work in this particular case. My function is a pretty straightforward alert:
function confirmEditProduct(editProductID){
alert("Worked");
}
This is my HTML code echoed in PHP:
echo "
<img src='$directory/$productImage' width='200px;'></img><br><br>
<p>Product Name: <p><input type='text' id='editName' name='editName' style='width:400px;' value='$productName'/>
<p>Category:
<select class='form-control' id='editCat' style='width:200px;' disabled>
<option value='Cacti'"; if ($productCategory == '1') echo " selected='selected'"; echo ">Cacti</option>
<option value='Succulents'"; if ($productCategory == '2') echo " selected='selected'"; echo ">Succulents</option>
</select>
<p>Description: <p><textarea rows='4' cols='50' id='editDesc' name='editDesc'>$productDesc</textarea>
<p>Price: <input type='text' id='editPrice' name='editPrice' value='$productPrice'/>
<p>Image: <input class='input-group' type='file' id='editImage' name='editImage' accept='image/*' />
<p>Stock: <input type='text' id='editStock' name='editStock' value='$productStock'/>
<p>
<input type='button' class='btn btn-success' id='$productID' onClick='confirmEditProduct($productID);' value='Edit Product' />
";
This snippet is part of a modal btw.
Thank you to everyone who can help me out

This seems like it would be quite simple. Are you also echoing the Javascript? If so, take an extra precaution and move it before the HTML code. Some other things you may want to consider include making the input button into a straight up button and omitting the semicolon at the end of the onclick attribute. As for styling, you may want to put the value attribute after the type attribute. Hope this helps!
Edit:
When I mean echoing the Javascript, make sure you have a <script src="main.js"> or the entire script within your echoed code.

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

javascript subscribe form change

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 :)

Fill textarea from input value in different divs

i am working on a upload section for my website.
When users want a new application to upload they need to fill out a form where the put the version number etc.
There are 27 different applications wich can be uploaded. for that i have made a while loop
example:
<select id="type">
<option value="choose" selected>choose here</option>
<?php
require("Function/applist.php");
while($showtablerow = mysql_fetch_array($showtablequery_result))
{
echo "<option value=".$showtablerow[0].">".$showtablerow[0]."</option>";
}
?>
</select>
</div>
<div id="choose" class="add" style="display:none;"></div>
<?php
require("Function/applist.php");
while($showtablerow = mysql_fetch_array($showtablequery_result))
{
echo "<div class='add' id=".$showtablerow[0]." style='display:none;'><h2 id='amx-label'>".$showtablerow[0]."</h2>
<div id='formadd' style='opacity:1;'>
<form name='addamx' id='addamx' method='post'>
<div id='version' class='uploadform' style='opacity:1;'>
Version: <input style='opacity:1;' required type='text' name='versie' id='versie' width='3' onchange='process1()' ><br>
</div>
<div id='date' class='uploadform' style='opacity:1;'>
Release Date(yyyy-mm-dd): <input required type='date' style='opacity:1;' size='10' maxlength='10' name='date' id='date'>
</div>
<div id='build' style='opacity:1;'>
Build By: <input required type='text' style='opacity:1;' size='5' maxlength='25' name='build' id='build' >
</div>
<div id='platform' style='opacity:1;'>
Platform: <span>32 Bit:</span><input required type='radio' style='opacity:1;' id='platform' name='platform' value='32bit'>
<span>64 Bit:</span><input required type='radio' style='opacity:1;' id='platform' name='platform' value='63bit'>
</div>
<div id='application'>
<input type='hidden' name='app' value=".$showtablerow[0]." />
</div>
<div id='notes' style='opacity:1;'>
Release Notes: <textarea id='notess' name='test' onblur='process1()'></textarea>
</div>
<div id='uploadfooter' style='opacity:1;'>
<button type='submit' id='uploadamx' name='uploadamx'>Upload
</div>
</form>
</div>
</div>";
}
?>
In the select box they choose wich application they want to upload, and depending on that selection they get a form.
In the text area they write their release notes.
I want that when they fill their version number that automatically that version number is filed in in the text area.
i got that kinda working with the following javascript:
function process1() {
var appname = document.getElementById('type').value;
var version = document.getElementById('versie').value;
var textvalue = "changes for " + appname + " version " + version;
document.getElementById("notess").value = textvalue;
}
the function works only for the first form div
When i try it on the second div that textarea stays empty and the version number from the second div gets inserted in the textarea from the first div
How i can make the function so that the textarea only gets filled with the version number from that form?
Any ideas?
EDIT***
the way AboQutiesh was the good startup, the only adjustment that it needed was
He wrote:
onblur='process1(".$showtablerow[0].")'
result was onblur='process1(argument)'
This didnt work because the argument needed onblur='process1('argument')'
because it is in a while loop i couldnt just put the '' because it would break up the entire onblure
thansk to a collegea of my who pointed me to the ascii table
SOLUTION:
i changed it to onblur=process1(&#39".$showtablerow[0]."&#39)
(delete the ; at the end of the asccii otherwhise it wouldnt show here properly)
Thanks for the startup AboQutiesh
you need to provide different ids for each text area like this in php :
<div id='notes' style='opacity:1;'>
Release Notes: <textarea id='notess_".$showtablerow[0]." name='test' onblur='process1(".$showtablerow[0].")'></textarea>
</div>
and in the js
function process1(appId) {
var appname = document.getElementById('type').value;
var version = document.getElementById('versie').value;
var textvalue = "changes for " + appname + " version " + version;
document.getElementById("notess_"+appId).value = textvalue;
}
i think that is what you need

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.

Categories

Resources