Form Resetting is not working using jquery - javascript

I want to reset the form after calling an ajax function.
This is the code i gave in the jquery:
$("#frm_silder").reset();
Here frm_silder is the id of form. But when I'm using this code i got an eorror message like this.
$("#frm_silder").reset is not a function
In my html i give the id to form like this:
<form name="frm_silder" id="frm_silder" method="post">
So what is the problem in my code?

In jQuery
$('#frm_silder')[0].reset();
in Javascript
document.getElementById('frm_silder').reset()

You need to reset each element individually. Jquery does not have a function reset() that works on a form. reset() is a Javascript function that works on form elements only. You can however define a new jquery function reset() that iterates through all form elements and calls the javascript reset() on each of them.
$(document).ready(function(){
$('a').click(function(){
$('#reset').reset();
});
});
// we define a function reset
jQuery.fn.reset = function () {
$(this).each (function() { this.reset(); });
}
Demo
Alternatively, if you don't want to define a function, you can iterate through the form elements
$(document).ready(function() {
$('a').click(function() {
$('#reset').each(function() {
this.reset();
});
});
});
Demo
Source

I followed the solution given by #sameera. But it still throw me error.
I changed the reset to the following
$("form#frm_silder")[0].reset();
Then it worked fine.

You can use the following.
#using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { #class = "" }))
{
<div class="col-md-6">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
#Html.LabelFor(m => m.MyData, new { #class = "col-form-label" })
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
#Html.TextBoxFor(m => m.MyData, new { #class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="">
<button class="btn btn-primary" type="submit">Send</button>
<button class="btn btn-danger" type="reset"> Clear</button>
</div>
</div>
}
Then clear the form:
$('.btn:reset').click(function (ev) {
ev.preventDefault();
$(this).closest('form').find("input").each(function(i, v) {
$(this).val("");
});
});

Related

Dynamic slideToggle function with given html class id parameters

I have a question about to creating dynamic jquery slideToggle function. I have html template as below:
<h4 id="client" class="section-title">
<div class="sect-icon"></div>
<span>Client Info</span> </h4>
<div class="form-row" id="client_data">
<div class="form-group col-md-4">
<label for="id_client_name">Name</label>
<input class="form-control" disabled value="{{client.client_name}}">
</div>
</div>
And jQuery function as :
$(document).ready(function () {
$("#client").click(function () {
if ($('#client_data').is(':visible')) {
$("#client").removeClass("section-title");
$("#client").addClass("section-title closed");
} else {
$("#client").removeClass("section-title closed");
$("#client").addClass("section-title");
}
$("#client_data").slideToggle("fast");
});
It is work . But this jQuery function is only for concreate html class. If i append another class to html ,then i should be copy this jQuery and past and edit id part. But i want to write one jQuery function for dynamic html id.
I mean how i can use above jQuery function for below html without creating new jQuery
<h4 id="equip" class="section-title">
<div class="sect-icon"></div> <span>Calibrated Equipment</span></h4>
<div class="form-row" id="equip_data">
<div class="form-group col-md-4">
<label for="id_brand_name">Brand</label>
<input class="form-control" disabled value="{{equip.brand_name}}">
</div>
</div>
When I was a university student, a teacher told us that repeated code is called "function":
function myStuff(idText) {
$("#" + idText).click(function () {
if ($('#' + idText + "_data").is(':visible')) {
$("#" + idText).removeClass("section-title").addClass("section-title closed");
} else {
$("#" + idText).removeClass("section-title closed").addClass("section-title");
}
$("#" + idText).slideToggle("fast");
}
And you pass the id to myStuff whenever you want, like:
$(document).ready(function () {
myStuff("client");
});

POST request doesn't recognize in my controller using Opencart

I have a problem in my code. In my setup I created a single page for language selection. And I copy some of opencart's code on language template and also on controller. But my problem is after passing my form, the action controller doesn't get any POST data from my form.
<form action="{{ action }}" method="POST" enctype="multipart/form-data" id="form-language">
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>ENGLISH</h3>
<button class="language-select btn btn-green" type="button" name="en-gb">Choose</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>日本語</h3>
<button class="language-select btn btn-green" type="button" name="jap">選択</button>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="border_index_in">
<div class="holder">
<h3>中文</h3>
<button class="language-select btn btn-green" type="button" name="zh-hk">选择</button>
</div>
</div>
</div>
</form>
JS:
// Language
$('#form-language .language-select').on('click', function(e) {
e.preventDefault();
$('#form-language input[name=\'code\']').val($(this).attr('name'));
$('#form-language').submit();
});
Controller to show my language selection page
public function language_switch() {
$this->load->model('setting/extension');
$this->document->setTitle($this->config->get('config_meta_title'));
$this->document->setDescription($this->config->get('config_meta_description'));
$this->document->setKeywords($this->config->get('config_meta_keyword'));
if (isset($this->request->get['route'])) {
$this->document->addLink($this->config->get('config_url'), 'canonical');
}
$data['action'] = $this->url->link('common/language/language');
$data['code'] = $this->session->data['language'];
$styles_array = array(
'catalog/view/theme/onemidorie/stylesheet/style.css'
);
$scripts_array = array(
);
foreach($styles_array as $st) {
$this->document->addStyle($st);
}
foreach($scripts_array as $sc) {
$this->document->addScript($sc);
}
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$this->response->setOutput($this->load->view('common/language_selection', $data));
}
Controller that should accept the POST data from my form:
public function language() {
print_r($this->request->post['code']); //Notice: Undefined index: code
die;
if (isset($this->request->post['code'])) {
$this->session->data['language'] = $this->request->post['code'];
}
if (isset($this->request->post['redirect'])) {
$this->response->redirect($this->request->post['redirect']);
} else {
$this->response->redirect($this->url->link('common/home'));
}
}
Can you help me this?
You should use
print_r($this->request->post);
die;
Then you will get some post data.
because you define the name like "en-gb","jap" and "zh-hk". So please use above code then you can get solution.
You're not posting any data - you're just showing a button. Use something more like
<input type="submit" value="english" name="lang"/>
<input type="submit" value="japanese" name="lang"/>
etc. then just look at
$_POST['lang']
and see if it's english, japanese or whatever.
You can find out how opencart set language in /catalog/controller/startup/startup.php:
// Overwrite the default language object
$language = new Language($code);
$language->load($code);
$this->registry->set('language', $language);
So in controller what should accept the POST data you should dublicate this code before loading language:
// $this->request->post['code'] = 'en-gb' or 'ru-ru' or whatever.
$language = new Language($this->request->post['code']);
$language->load($this->request->post['code']);
$this->registry->set('language', $language);
// now opencart use new language and you can use it too:
$this->load->language('common/header');
$text_home = $this->language->get('text_home');
This works for me in opencart 2

.submit(function ()) inside my modal popup is not working, and my modal popup will send normal http post request

I am working on an asp.net mvc web application. on my main view i got the following create link:-
<a class="btn btn-success" data-modal="" href="/Staff/Create" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
and i have the following script:-
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('#myModalContent', dialog).submit(function () {
if ($('#myModalContent').valid()) {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
}
else {
return false;
}
});
}
Now when i click on the Create link the Create action method that will return the following partial view, which will be rendered inside a modal popup :-
#model SkillManagement.Models.Staff
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Staff</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.GUID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GUID)
#Html.ValidationMessageFor(model => model.GUID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsExternal, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IsExternal)
#Html.ValidationMessageFor(model => model.IsExternal)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
//code goes here
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
till now i have every thing working well, the Get Create action method will be called and the partial view will be rendered inside a modal popup.
but now inside my partial view if i click on "Create" button , the Post create action method will be called but not due to the javascript code . and when i check Request.IsAjax() inside my Post create action method, i got that it is not an ajax request which means the partial view send a normal Post http and not ajax request as defined inside the script,, can anyone advice what is wrong in my current approach ?
Thanks
as you can see you just pass the #myModalContent node to the bindForm function, and jQuery selector looks for
// will never find #myModalContent
$('#myModalContent', myModalContentDOMElement).submit(function () {
Instead you should do something like this
$('form', dialog).submit(function (e) {
e.preventDefault(); // stop the default form submit action
You are loading your form into the page via ajax, but the form you are loading is a regular html form if you want the form itself to use ajax, I believe are looking for #Ajax.BeginForm().
msdn documentation
#using (Ajax.BeginForm({objectparams})){
...

Html.BeginForm how to avoid multiple form submission?

We have the following code for registration page
#using (Html.BeginForm(MVC.Account.Register(Model.ReturnUrl), FormMethod.Post, new { #id = "register-form" }))
{
<div class="control-group clear">
#Html.LabelFor(m => m.Email)
#Html.TextBoxFor(m => m.Email, new { type = "email", #class = "forbid-lt-gt" })
<span class="hint raise">Will be user as Username.</span>
<div class="error">#Html.ValidationMessageFor(m => m.Email)</div>
</div>
<div class="control-group clear">
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
<span class="hint raise">Length between 6 and 10 characters</span>
<div class="error">#Html.ValidationMessageFor(m => m.Password)</div>
</div>
<div class="control-group clear">
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword)
<div class="error">#Html.ValidationMessageFor(m => m.ConfirmPassword)</div>
</div>
<div class="control-group action">
<button class="btn primary" type="submit">
<span>Sign up</span>
</button>
</div>
<div class="clear"></div>
}
And the file formBlocker.js to prevent multiple button click
$(function() {
$('form').one('submit', function () {
$(this).find('button[type="submit"]').attr('disabled', 'disabled');
});
//Enable submit button if data has changed
$('form').live("input", function () {
$(this).find('button[type="submit"]').removeAttr('disabled');
});
});
Usually all is fine, but sometimes it doesn't work and after user clicks several times on button the form can be sent several times to server. Early we had issue that after a click on submit button in IE form was sent to server twice. Now we don't have this issue but it was't fixed.
live is dead. dead. It was deprecated in 2.7 and removed in 2.9. DEAD!
I would use this approach:
var serializedData;
$(function () {
$('form').submit(function () {
var tempSerializedData = $(this).serialize();
if (tempSerializedData != serializedData)
serializedData = tempSerializedData;
else
return false;
});
});
Try this Not sure but this is working for me
$('form').one('submit', function () {
$(this).find('button[type="submit"]').attr('disabled', 'disabled');
setTimeout(function () {
$(this).find('button[type="submit"]').attr('disabled', 'disabled');
}, 20);
});

Jquery click function, using this but return me window object

all. I have html layout like this:
<div class="row" id="1">
/*Other code has nothing to do with <div class="form-group col-lg-1">*/
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" onclick="updateLine()" value="Update">
</div>
</div>
I want to obtain the div's ID, in this case, which is 1.
This is what I did.
function updateLine() {
alert(this.parent().parent().attr("id"));
}
However, it failed, then I check
alert(this);
it returns to me the window object.
So the question is , how could I get the id's value, which is 1.
Thanks.
You need to pass this to the function as follows
<input type="button" class="btn btn-default" onclick="updateLine(this)" value="Update">
function updateLine(obj) {
alert(obj);
$(obj).closest('.row').attr('id'); // will return the id, note that numeric values like 1 are invalid
}
You do not need to pass this to the function. In an event handler this is the element clicked. However, to use .parent() etc on it you need the jQuery object for that element which is $(this)
Also, I would strongly recomment using .closest instead of .parent().parent(). Something like
$(this).closest('div.row').attr('id')
Way less likely to break when you make small layout changes...
The comments about using jQuery events instead of inline javascript are also good advice.
Example:
<div class="row" id="1">
/*Other code has nothing to do with <div class="form-group col-lg-1">*/
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" value="Update">
</div>
</div>
<script type="text/javascript">
$(function(){
function updateLine(event){
alert( $(this).closest('.row').attr('id') );
}
// If you have other buttons add a class like 'btn-update' and use that instead
$('body').on('click', '.btn-default', updateLine);
});
</script>
If you want to do inline event handlers, you need to pass this:
onclick="updateLine(this)"
then in js:
function updateLine(obj) {
alert($(obj).closest('.row').attr("id"));
}
However, I'd recommend removing the inline handler if possible and using jQuery to do the binding:
$('button').click(function() {
alert($(this).closest('.row').attr("id"));
});
What you are trying do is very bad practice. It will never work.
Firs, you should not use inline javascript.
Second, you should use real jQuery code.
Below you can see a working example.
<div class="row" id="1">
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" value="Update" id="someID" />
</div>
</div>
And your jQuery code should be like:
$(function () {
$('#someID').click(function () {
alert($(this).parents('div:eq(1)').prop('id'));
});
});
Here is a working example: http://jsfiddle.net/avramcosmin/Z9snq/
A bit late but what worked for me:
$(document).on('click', '.id', function(event) {
const elem = $(this);
})

Categories

Resources