Jquery - Getting a parent element's data-id - javascript

been looking through previously asked questions but can't find much help.
I have the following html code that sends through a data-id to the following modal, when the user submits the form i have created a ('#edit-form').submit function which needs to send through the previously mentioned data-id.
Here's my code
Button to Open Modal >>
<button type="button" class="edit-group" title="Edit Group" data-id="<?php echo $group->id ?>" data-name="<?php echo $group->groupName ?>">Edit Group</button>
Form inside modal:
<form class="form-horizontal" id="edit-template-form">
<div class="modal-body">
<div class="form-group">
<label for="edit-group-name" class="col-sm-2 control-label">Group name</label>
<div class="col-sm-10">
<input type="text" name="groupName" class="form-control" id="edit-template-name" placeholder="New Group Name">
</div>
</div>
<input type="hidden" id="edit-template-id">
</div>
<div class="modal-footer">
<button type="button" class="md-close" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary btn-flat">Save Changes</button>
</div>
</form>
Jquery
$('#edit-template-form').submit(function (e) {
e.preventDefault();
var data = {
id: $(this).parent().val($(this).data('id')),
name: $('#edit-template-name').val()
};
console.log(data);
return false;
});

this keyword refers to data object itself not #edit-template-form. So store the variable this before using it like below:
$('#edit-template-form').submit(function (e) {
e.preventDefault();
var form = $(this);
var data = {
id: form.parent().val(form.data('id')),
name: $('#edit-template-name').val()
};
console.log(data);
return false;
});

Related

Unique comment section per dynamic modal

I have a webpage with dynamically loaded cards that pop up into individual modals to display more data. These modals all have their unique id in order to pop up the correct one.
I am attempting to put a unique comment section for each modal. What I have implemented works only for the first modal & doesnt even show the comments on the second modal onwards.
I would appreciate some direction in how to make them display per modal & how to make them unique. I am assuming I echo $test[id] just like I used for the modals. Need a little assistance in script side of things.
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
</div>
</div>
<script>
var data = 1;
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
UPDATE:
Going with the response received, I made certain changes & noticed that even though the comment form is visible on all modals, the posted comments itself
only appear on the first modal. With a bit of hardcoding I am able to tell that the display_comment(id) in html & script needs to be same. The HTML id updates as per console, but I am unable to pass the correct id to $('#display_comment'+myData1).html(data); (it is always 1).
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
</div>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
var myData1 = $("#dom-target").data("id");
console.log('#display_comment'+myData1);
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
I have also tried the following & simply receive undefined as the value in console for myData2:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {
myData2: $("#dom-target").data("id")
},
you should loop all the content according to your $test['id'].
each loop will generate each $test['id'], modals, form.
therefore, you will have multiple form according to each modals.
regarding the name of the input box (name="comment_id","comment_name" etc), just use the same name, as this will affect your backend on how you will process those input ($_POST['']).
this shouldn't be an issue if you area using same input name as user can only submit 1 form on each request.
just the value will be changing based on the form.

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

How to dynamically Add/Remove file type input field using jquery?

I cannot remove input field dynamically, I can add field but my remove option is not working.
I am using jquery for dynamically add/remove field and bootstrap 3 for my layout.
Here is my markup:
<div class="row margin-bottom">
<div class="col-md-12 col-sm-12">
<button type="submit" class="add-box btn btn-info"><span class="glyphicon glyphicon-plus"></span> Add More Fields</button>
</div>
</div>
<?php $attributes = array('class' => 'form-horizontal', 'role' => 'form'); echo form_open_multipart('config/upload_image', $attributes);?>
<div class="text-box form-group">
<div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput"/></div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-upload"></span> Upload</button>
</div>
</div>
<?php echo form_close();?>
Here is my jquery code:
$(document).ready(function(){
$('.add-box').click(function(){
var n = $('.text-box').length + 1;
if(n > 5)
{
alert('Only 5 Savy :D');
return false;
}
var box_html = $('<div class="text-box form-group"><div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput'+ n +'"/></div><div class="col-sm-2"><button type="submit" class="remove-box btn btn-danger btn-sm"><i class="fa fa-minus-circle fa-lg"></i></button></div></div>');
$('.text-box:last').after(box_html);
box_html.slidedown('slow');
});
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).parent().remove();
return false;
});
});
The error is in the remove button click event handler. You need to remove the closest form group rather than the immediate parent:
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).closest(".form-group").remove();
return false;
});
check this bootply for a working example: http://www.bootply.com/x8n3dQ6wDf
EDIT
for animation on remove you can use jQuery slideUp like this:
$('.form-horizontal').on('click', '.remove-box', function(){
var formGroup = $(this).closest(".form-group");
formGroup.slideUp(200, function() {
formGroup.remove();
});
return false;
});

field empty error for pop-up form

Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact

Categories

Resources