Display value of javascript variable in div - javascript

Good day all,
I have the following html code
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
and, I have the following javascript code
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia =
'<div class="blog_comm_hold"> \
<div class="user_comment_photo1"></div> \
<div class="blog_comment_"> \
<div class="blog_com_text">\
comment\
</div>\
</div>\
<br>\
</div>';
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
</script>
What I am trying to do is have the value that I typed into the textarea field of the form be displayed after the form when the user hits the enter key. The div classes load well but I don't know how to go about getting the actual value from the var variable be displayed too.
The var comment variable as can be seen above is not displaying its value. The variable is found under the blog_com_text div in the above script.
I want that when the user hits the enter key, that the value of the above comment variable is loaded inside of the respective div based on the above code. The div classes load well with no issue but how to have the value of the variable be loaded too.
Thanks much.

Here you go with the solution https://jsfiddle.net/xabt3vgt/
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
//$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
// function(data) {
var newmedia =`<div class="blog_comm_hold">
<div class="user_comment_photo1"></div>
<div class="blog_comment_">
<div class="blog_com_text">
${comment}
</div>
</div>
<br>
</div>`;
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
//});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
You just need to uncomment you php ajax call.
Use back tick ` (left to 1) in the keyboard and if you want to add any variable then use ${variable_name} in between the back tick.

Try this
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment));
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
You can test with this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="post_blog_comment"></div>
<textarea id="blog_comment"></textarea>
<input type="button" value="Go" id="postcomment" />
<script type="text/javascript">
$('#postcomment').click(function() {
showcomment();
});
function showcomment() {
var comment = $("#blog_comment").val();
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment);
$('#post_blog_comment').after(newmedia);
$("#blog_comment").val('');
}
</script>

Related

textarea not send form do not send form the first click to send. The at 2 click yes

In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;

How do I keep single checkbox stay checked after refreshing the page?

HTML code:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
This will make the checkbox stays checked, but when page is refresh or exit and comes back, the checkbox will be unchecked. Therefore, after some research, I tried the localStorage, but doesn't seem to quite figure it out yet.
localStorage code:
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
I have script tags around the localStorage code and after implementing these codes, my checkbox still doesn't stays checked.
Both code as a whole:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" name="new_background"/>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
</script>
<input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>
I would like to thank everyone that took time to help me figure out the solution to my question with the biggest thanks to #Pranav C Balan!!! Check out the finished code # http://stackoverflow.com/a/44321072/3037257
I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.
One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
</div>
Working demo : FIDDLE
<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
});
</script>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
Working demo : FIDDLE
An alternative to localStorage that only utilizes document.cookie:
$('input:checkbox').change(function() {
saveCookies();
});
To register the function and the actual function:
function saveCookies() {
var checkArray = [];
$('input.comic-check').each(function() {
if ($(this).is(':checked')) {
checkArray.push(1);
} else {
checkArray.push(0);
}
});
document.cookie = "checks=" + checkArray;
}
This is an alternative to localStorage, and depends on whether you want it to persist longer
And to retrieve the saved (on load)
var checks = getCookie("checks");
if (checks != "") {
checkArray = checks.split(',');
//unchecks boxes based on cookies
//also has backwards compatability provided we only append to the list in landing.ejs/generator.js
for (var i = 0; i < checkArray.length; i++) {
if (checkArray[i] == "0" && $('input.comic-check').length > i) {
var checkBox = $('input.comic-check')[i];
$(checkBox).prop('checked', false);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Three situations you will need to check the checkbox
PHP have it set to checked="checked" (checked)
localStorage have it as true (checked)
all other situations this should be unchecked
all you need is to make sure first two situation you check the checkbox, then by default it is unchecked, but in your each you are also uncheck checkbox, therefore ignored the PHP part (as php set it to checked but localStorege set it to unchecked)
Example here: https://jsfiddle.net/dalinhuang/efwc7ejb/
//on page load
$.each(checkboxValue, function(key, value) {
if(value){
$("#" + key).prop('checked', value);
}
});
I would change:
<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>
for:
<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>
In inline HTML, you don't need the checked attribute to be checked=checked.
Just checked is enought.
checked=checked is used in JavaScript to programatically check a checkbox.
EDIT
About your localStorage...
I made an example for you on CodePen
//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
$("#" + key).prop('checked', value);
});
// ================ Saving checks
// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");
// On change handler.
allCheckboxes.on("change", function() {
// Check how many checkboxes we have.
var jsonCheckboxes = {};
console.log("There is "+allCheckboxes.length+" checkboxes.");
// Building the json.
for(i=0;i<allCheckboxes.length;i++){
console.log(allCheckboxes.eq(i).attr("id"));
console.log(allCheckboxes.eq(i).is(":checked"));
jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
}
console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));
// Setting localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
Working around your comment : my goal is to find something that will make my checkbox stays checked if the user choose to, here's a way to have the localStorage handle it :
jQuery (3.2.1)
$(document).ready(function() {
var bground = localStorage.getItem('background'); // get the value if exists
if (bground == 'shadow') { // checkbox has been previously checked
$('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
$('#checker').attr('');
}
$('#submit').submit(function() { // when form is submitted
bground = localStorage.getItem('background'); // get the value in LS
if($('#checker').is(':checked')) // is it checked or not ?
{ sh = 'shadow'; } else { sh = 'shadowless'; }
localStorage.setItem('background', sh); // update LS with new value
});
});
HTML (added id="submit" to form)
<form action="" id="submit" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
This will make the checkbox stays checked, and when page is refreshed, the checkbox will be checked/unchecked depending on user's previous choice.
You could also use the jQuery change function instead of form submitting.
Just modify the line :
$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line

Getting hidden values and matching in jquery, javascript and html

I have a template that will consists of 2 hidden fields and 1 checkbox. The template is rendered and appended to the html page using a function addProductImage().
How can I go about getting the value of the hidden fields (thisFile and mainImage)? The id of the div is dynamic gc_photo_{{id}}_{{filename}}, it look something like this gc_photo_1234_12dhbc.jpg .
After getting the value of the two hidden fields, I want to match the 2 values and see if it is ===, if is it will set the checkbox to checked.
Code for the template
<script type="text/template" id="imageTemplate">
<div class="row gc_photo" id="gc_photo_{{id}}_{{filename}}" style=" border-bottom:1px solid #ddd; padding-bottom:20px; margin-bottom:20px;">
<div class="col-md-2">
<input type="hidden" name="thisFile" value="{{filename}}"/>
<input type="hidden" name="mainImage" value="<?php echo $biz_product->image_name;?>"/>
<input onclick="return set_parentimage(this);" type="radio" name="primary_image" id="{{id}}_{{filename}}" value="{{id}}" {{#primary}}checked="checked"{{/primary}} /> <?php echo lang('main_image');?>
</div>
</div>
</script>
Code for the function
function addProductImage(val)
{
view = {
id:val.item_id.replace(/\s/g, ''),
filename:val.detail_image_name,
alt:val.alt,
primary:val.primary,
caption:val.caption
}
var output = Mustache.render(imageTemplate, view);
$('#gc_photos').append(output);
$('#gc_photos').sortable('refresh');
thisFile = $($('#gc_photo_id_filename').find("input")[0]).val();
mainImage = $($('#gc_photo_id_filename').find("input")[1]).val();
alert(thisFile);
alert(mainImage);
if(thisFile === mainImage)
{
alert('true');
}
else
{
alert("different");
}
photos_sortable();
}
}
Update 1
Code for the function
function addProductImage(val)
{
view = {
id:val.item_id.replace(/\s/g, ''),
filename:val.detail_image_name,
alt:val.alt,
primary:val.primary,
caption:val.caption
}
var output = Mustache.render(imageTemplate, view);
$('#gc_photos').append(output);
$('#gc_photos').sortable('refresh');
thisFile = $($('#gc_photo_id_filename').find("input")[0]).val();
mainImage = $($('#gc_photo_id_filename').find("input")[1]).val();
alert(thisFile);
alert(mainImage);
if(thisFile === mainImage)
{
$('[name="primary_image"]').prop('checked', true);
}
else
{
alert("different");
}
photos_sortable();
}
}
thisFile = $(output).find("[name='thisFile']").val();
mainFile = $(output).find("[name='mainFile']").val();
you can get values of thisFile and mainFile this way.

jQuery client side password verification

first of all I'd like to say I realise it's not a secure method.
This is only for training purpose.
The algorhitm should be:
click on a div with id="login-bg"
app displays the banner
provide the code
if the code's ok set cookie and fade out the banner
if the code's not ok the div shakes (still remaining on the screen)
if you don't want to provide the code press 'cancel' and fade out the banner
Set cookie function (it works fine):
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<script type="text/javascript">
function SetPwd(c_name,value,expiredays){
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+";path=/"+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
</script>
<?php } ?>
And here must be the problem with jQuery:
<?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy"/>
</form>
<h3>And enjoy free access!</h3>
<a id="cancel">Cancel</a>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
if( document.cookie.indexOf("is_logged") ===-1 ){
$('#video').click(function(){
$("#login-bg").fadeIn('slow');
});
$('#cancel').click(function(){
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
}
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
});
</script>
<?php } ?>
In my opinion the value '#code' id not passed to jQuery from the form.
But I may be wrong.
Do you have any ideas. Could you make it work?
Thanks for your help.
looks to be a problem here..
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
this will not equate the way you want it to:
if( value == test )
I would suggest changing it to,
if( value == pass )
also change
$("#submit").click(
to
$("#enjoy").click(
I've changed. However, the system still does not behave as it should. When I click 'submit' the banner just disappears ( doesn't matter if the code is ok or not ).
I think the value is not passed because when I do a simple test there's any alert:
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
alert(value);
if( value == pass ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
Yes, your click handler for the submit was not correct and at the password check you've missed the quotes 'test'. (As the others already answered.)
Below is the demo of your code and here at jsFiddle. It uses the jQuery cookie plugin for the cookies, but your PHP cookies will work too. I have just no backend for the demo.
Sorry, it's not working on SO because of insecure operation, probably the cookies are not allowed here. But at jsFiddle it is working.
Also don't remove the login div with $("#login-bg").remove(); because it will be removed from DOM and you can show it again to the user. It's better to only hide it.
// if(!isset($_COOKIE['is_logged']))
$(document).ready(function () {
if (!$.cookie('is_logged')) {
console.log('not logged in, show form');
//document.cookie.indexOf("is_logged") === -1) {
//$('#video').click(function () {
//$('#code').val(''); // clear input
$("#login-bg").fadeIn('slow');
//});
$('#cancel').click(function () {
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
} else {
$('#mainContent').fadeIn('slow');
}
$('#logout').click(function () {
console.log('hide clicked');
$('#code').val(''); // clear input
$('#mainContent').hide();
$("#login-bg").fadeIn('slow');
$.removeCookie('is_logged');
});
$("#check-form").on('click', 'input[type=submit]', function (evt) {
evt.preventDefault();
var value = $('#code').val();
var pass = 'test';
if (value == pass) { // 'test') {
//SetCookie('is_logged', 'is_logged', 365 * 10)
$.cookie('is_logged', 'true', {
expires: 7
});
$('#mainContent').fadeIn('slow');
$("#login-bg").hide(); // don't remove the login section
} else {
$('#login-bg').effect("shake");
}
});
});
#login-bg {
display: none;
}
#mainContent {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy" />
</form>
<h3>And enjoy free access!</h3>
<a id="cancel" href="#">Cancel</a>
</div>
</div>
<div id="mainContent">
<strong>Login succeeded!</strong> Shown after login!!
<a id="logout" href="#">Logout</a>
</div>

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

Categories

Resources