I tried validation on HTML element which get printed via PHP but it is not working, but it does work when I put the same HTML without PHP.
Below is the HTML in which the actual data will be printed via AJAX:
<div class="row" id="live_data">
// here will all radio buttons and images echo via ajax
</div>
Here is the AJAX:
function fetch_all() {
var form_name = 'package_form2';
$.post('ajax/ajax_form_get_all_packages.php',{form_name:form_name}, function(result) {
console.log(result);
$('#live_data').html(result);
});
} fetch_all();
Here is the actual data which gets echoed via Ajax:
$output .= '
<div class="col-md-4">
<label for="'.$id.'">
<img src="uploads/'.$img.'" class="img-responsive">
</label>
<div>
<div class="radio text-center">
<input type="radio" id="'.$id.'" value="'.$code.'" name="optradio" class="optradio">
</div>
</div>
</div>
';
Here is the code of FormValidation:
$(document).ready(function() {
$('#menu1_info').formValidation({
message: 'This value is not valid',
icon: {
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
optradio: {
validators: {
notEmpty: {
message: 'Please choose one of the Package'
}
}
}
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var fv = $form.data('formValidator');
$form.bootstrapValidator('disableSubmitButtons', false);
});
});
There is no element with class optradio in your markup. Instead there is one with attribute name equal to optradio:
$(document).on('change', '[name="optradio"]', function() {
alert("Radio button clicked");
});
UPDATE
If I understood correctly, #menu1_info element comes from the ajax response
$(document).ready(function() {
$('#menu1_info').formValidation({
Here you are trying to select an element on document ready, but this element is not present to the DOM yet because it is appended asynchronously (after document ready event).
So, you have to initialize your plugin after the target element is present to the DOM (in the ajax callback function).
// The $('#menu1_info') element is not present now
$.ajax({
url: '...',
...,
success: function(data) {
// Append data from ajax call
$('#target').append(data);
// Now, $('#menu1_info') element is present
$('#menu1_info').formValidation({ ... });
}
});
There is no such element in the response '.optradio'.
Better to change to this:
$('#live_data').on('change', ':radio', function() {
alert("Radio button clicked");
});
Also you can delegate to closest static parent which in your case is #live_data
Related
I have a delete hyper link
Delete
and my Jquery function
$(document).ready(function()
{
$("#password_validate").validate({
rules:{
current_pwd:{
required: true,
minlength:6,
maxlength:20
},
new_pwd:{
required: true,
minlength:6,
maxlength:20
},
confirm_pwd:{
required:true,
minlength:6,
maxlength:20,
equalTo:"#new_pwd"
}
},
errorClass: "help-inline",
errorElement: "span",
highlight:function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
}
});
$("#delCategory").click(function(){
alert("Test");
if(confirm('Are you sure you want to delete this Category?')){
return true;
}
return false;
});
});
My other parts of the code can access the #password_validate and make sure the password field is required and all. But the #delCategory from the same HTML page is unable to access the function and return confirmation.
I am able to call the Jquery function from Chrome Console and get the pop-up and confirmation, but my href is failing to call it and it processes the delete without confirming.
Add event.preventDefault() to your click(...) event handler to prevent the default action/behaviour that belongs to the event from occurring. i.e:
Event.preventDefault()
<form method="POST" action="{{ url('/admin/delete-category/'.$category->id) }}">
#csrf
#method("DELETE")
<input type="hidden" name="id" value="{{$category->id}}">
<input id="delCategory" type="submit" class="btn btn-danger text-center btn-mini" value="Delete">
</form>
jQuery
$("#delCategory").click(function (e) {
e.preventDefault();
if (!confirm('Are you sure you want to delete this Category?')) {
return;
}
const $form = $(this).closest("form");
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: {
"_method": $form.find("input[name=_method]").val(),
"_token": $form.find("input[name=_token]").val(),
"id": $form.find("input[name=id]").val()
}
});
});
ADDENDUM
If you have multiple "delete" buttons in a single document, you may consider using a class=... attribute instead of id=....i.e:
<!-- Instead of: -->
<input id="delCategory" ...> ❌
<!-- Use this: -->
<input class="delCategory" ...> ✅
Modify the JavaScript accordingly. i.e:
$(".delCategory").click(function (e) {
// ...
That would ensure that the event handler is applied to all relevant 'dom' elements with a particular class attribute instead of a single dom element matching a unique id attribute.
Resources:
What's the difference between an id and a class?
What is the difference between id and class in CSS, and when should I use them?
I am trying to submit a form with dynamic inputs. I am able to add a several inputs via the javascript. However, when I submit, it only picks up the first added input value. I hope someone can take a look at this for me as I've tried to fix this for so long. Thank you
Controller
public function update(){
$this->form_validation->set_rules('first_name', 'Firstname', 'trim|required|xss_clean');
$this->form_validation->set_rules('last_name', 'Lastname', 'trim|required|xss_clean');
$this->form_validation->set_rules('phone_number', 'Phone', 'trim|required|xss_clean');
$this->form_validation->set_rules('date_of_birth', 'Date of Birth', 'trim|required|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('country', 'Country', 'trim|required|xss_clean');
$this->form_validation->set_rules('active', 'Is Active', 'trim|required|xss_clean');
$id = $this->input->post('id');
$person_id = $this->input->post('person_id');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$date_of_birth = $this->input->post('date_of_birth');
$phone_number = $this->input->post('phone_number');
$account_number = $this->input->post('account_number');
$address = $this->input->post('address');
$country = $this->input->post('country');
$active = $this->input->post('active');
if($this->form_validation->run()==false){
$this->edit();
}else{
$person = array(
'first_name'=>$first_name,
'last_name'=>$last_name,
'date_of_birth'=>$date_of_birth,
'phone_number'=>$phone_number,
'address'=>$address,
'country'=>$country,
);
$account = array(
'is_active'=>$active
);
print_r($account_number);
}
}
View
<script>
$(document).ready(function(){
var max_fields = 5;
var wrapper = $("#new_account_number_container");
var addInput = $("#addInput");
var i;
$(addInput).click(function(e){
i = $("#new_account_number_container input").length;
e.preventDefault();
if(i<max_fields){
i++;
$(wrapper).append('<div><input type="text" name="account_number[]" class="form-control" placeholder="Account Number" required autofocus>Remove<div>');
}
});
$(wrapper).on("click",".remove", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
i--;
});
});
</script>
<div id="new_account_number_container" class="form-group col-sm-8">
<input type="text" name="account_number[]" class="form-control" placeholder="Account Number" autofocus>
<br>
</div>
<div class="form-group col-sm-8">
<button class="pull-right btn btn-primary" id="addInput">Add</button>
</div>
First thing, I can not see <form> in your code. Without this tag, you can not get desired behaviour:
After that,
To give you formatted code snippet I am posting that suggestion as an answer:
// this is the id of the form
$("#form_id").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_id").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
We need to remember that, PHP serves as back-end application. So anything dynamic (like DOM input text in your case) may NOT be submitted simply because the <form> tag is not updated that you have new text-box input.
One of the thing you could do is to use ajax for form submitting. Because it is Client-Side Script, it could detect all DOM input text box on your page, and serialized it before send the request to the back-end.
First by adding a <form> tag between your input and button component. Example like <form id="frm" name="frm">.
Second, by adding a button which trigger a JavaScript function.
function update(){
if(confirm("Are you sure?")==true){
$.post(
"*absolute_project_root_path*/*controller*/update",
$('#frm').serialize(),
function(response){
//what to do with your response..
}
);
}
return false;
}
Then you can access the submitted form in the back-end like usual.
I've been trying to use stripe to accept payment and I've been trying to make a rough prototype for it from a guide I found but I can't seem to get it working. The new input named "stripeToken" never inserts after the submit. This causes my PHP script to never execute. I'm trying to understand why it never inserts. Here's the scripts:
Javascript: (In the head of page)
<script src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('mykeyishere');
</script>
<script>
// Event Listeners
$('#payment-form').on('submit', generateToken);
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
</script>
HTML/Javascript: (Tried JS both in the head and in the form)
<form action="index.php" method="POST" id="payment-form">
<script>
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};</script>
<span class="payment-errors"></span>
<div class="row">
<label>
<span>Card Number</span>
<input type="text" data-stripe="number">
</label>
</div>
<div class="row">
<label>
<span>CVC</span>
<input type="text" data-stripe="cvc">
</label>
</div>
<div class="row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" data-stripe="exp-month">
</label>
<input type="text" data-stripe="exp-year">
</div>
<button type="submit">Submit</button>
</form>
You should remove that script tag from inside the form and put it next to the other script tag.
also try wrapping your event binding in a document.ready
$(document).ready(function(){
$('#payment-form').on('submit', generateToken);
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
});
From what I can guess ( and its not a good guess), is that the #payment-form does not get bound correctly because the script is getting ran before the dom is ready?
Also another thing caught my eye. You have e.preventDefault() which stops the form from being submitted, but then you have a responsehandler. does that response handler get called? Is there some request that goes out to stripe and comes back?
Check in your network window and see if that is happening. The form only gets submitted in the form.get(0).submit(); part of the response handler, so after stripe completes.
I have an html page with some checkboxes:
<div class="col-md-2">
<div class='form-group employe-admin-contactP'>
<input type="checkbox" class="readymade-checkbox admin" name="" id="admin-${member?.user?.id }" data-id="${member?.user?.id }"
<g:if test="${member?.isAdmin()}">
checked
</g:if>
/>
<label for="admin-${member?.user?.id }" name="" class="readymade-label admin"></label>
</div>
</div>
Each time the user click on the checkbox (check/uncheck) a the following function which I wrote in js file have to be triggered:
$(document).ready(function() {
$('.readymade-checkbox.admin:not(checked)').on('click',function(){
var contact = {id:$(this).data('id') }
$.ajax({
url: makeUserAdmin,
type: "post",
data: {
id: JSON.stringify(contact), companyId: $('#teamCompanyId').val()
},
success: function (data, textStatus) {
jQuery("#updateCompanyteam").html(data);
}
})
return false;
});
})
The problem is that this the function is triggered only once.
I bet that jQuery("#updateCompanyteam").html(data); will modify the HTML area of the checkbox ".readymade-checkbox.admin". You need a persistant listener for your click event (which will be available even if the DOM is modified), or to refresh your listeners.
This issue has been already resolved in several threads like this one.
Cheers
I am having strange problem.
My submit button only works if I reedit any field.
If i press submit button becoming disable.
Then i need to reedit date field (any field require validation) then I can submit the form.
Note:Even reediting any field,didn't work on jsfiddle(submit button still disable).But reediting works on my project!
Here is my code
Jsfiidle Link
$(document).ready(function() {
$('#reportForm')
.bootstrapValidator({
// Only disabled elements are excluded
// The invisible elements belonging to inactive tabs must be validated
excluded: [':disabled'],
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
reportStartDate: {
validators: {
notEmpty: {
message: 'Please select Date'
}
}
},
reportEndDate: {
validators: {
notEmpty: {
message: 'Please select Date'
}
}
}
}
})
// Called when a field is invalid
.on('error.field.bv', function(e, data) {
// data.element --> The field element
var $tabPane = data.element.parents('.tab-pane'),
tabId = $tabPane.attr('id');
$('a[href="#' + tabId + '"][data-toggle="tab"]')
.parent()
.find('i')
.removeClass('fa-check')
.addClass('fa-times');
})
// Called when a field is valid
.on('success.field.bv', function(e, data) {
// data.bv --> The BootstrapValidator instance
// data.element --> The field element
var $tabPane = data.element.parents('.tab-pane'),
tabId = $tabPane.attr('id'),
$icon = $('a[href="#' + tabId + '"][data-toggle="tab"]')
.parent()
.find('i')
.removeClass('fa-check fa-times');
// Check if the submit button is clicked
if (data.bv.getSubmitButton()) {
// Check if all fields in tab are valid
var isValidTab = data.bv.isValidContainer($tabPane);
$icon.addClass(isValidTab ? 'fa-check' : 'fa-times');
}
});
});
After spending half of my day finally found solution.The problem was 'name' attribute for button.Bootstrap validation having problem to understand form submitted or not!
When I use following way doesn't work!
<button type="submit" class="btn btn-warning" name="submit" value="showReport">Show Report</button>
With php code
if (isset($_POST['submit']))
Solution!
<button type="submit" class="btn btn-warning">Show Report</button>
With php code
($_SERVER['REQUEST_METHOD'] == 'POST')
I had the same problem but realised that I had targetted the container div and not the form-tag. Might save someone some time.