How to call function inside Javascript - javascript

<script type="text/javascript>
function submitMe() {
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
}
</script>
<input type="hidden" name="jsfields" id="jsfields" value="">
I'm searching the way to get checked Ids of Jstree in form submit. So this is what I get. However, how I can call this function in my program?

Use a click/submit event
$(form).submit(submitMe);
or
$('[type="submit"]').click(submitMe);
Don't forget to prevent the default event and then trigger it after the code:
function submitMe(e) {
e.preventDefault();
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
window.location = $(this).closest('form').submit();
}

Related

Cannot cancel form submission in jquery

I am trying to cancel form submission after button click.
When button is clicked i get some information from check-timetable-timing-conflict with json.
So i decide to cancel the form submission if the data coming with json is 1.
But it does not cancel form submission although i get 1.
<form role="form" method="POST" id="subform" name="subform">
...
...
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
}
});
}
</script>
In order to prevent the form from submitting you need to return false from the onclick function that is called when the button is clicked. Also to prevent ajax form submissions you can also add e.preventDefault(); like below.
Note: The same effect could be achieved if using the form's onsubmit method instead of the button's onclick method to call the function.
var select_course = function(e) {
e.preventDefault();
// your logic goes here
return false;
}
<form role="form" method="POST" id="subform" name="subform" >
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course(event);">placeholder</button>
</form>
Your issue is where the submit event listener is set up.
You need to move this block of code outside the check_conflict() function.
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
.submit(function(e){}) creates a handler for the submit event. In your code, you aren't creating the handler until after the check_conflict function makes it's asynchronous call returns. It's too late. You need the handler already in place when the user submits the form.
<script>
conflict = 0;
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
var select_course = function()
{
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
}
else {
// todo no conflict
}
});
}
</script>
The problem was because of asynchronous behaivor of ajax.
When i click the button, the form submission already starts.
So when i try to check the conflict condition in jquery the form submission has already finished. So i solved the problem by submitting the form just in the if condition in jquery where i get conflict=1 with document.subform.submit().
Before the solution, i was starting the form submission, then i was doing jquery checks.
But now i first make jquery checks, then i do or not do form submission according to jquery search results.
<form role="form" method="POST" id="subform" name="subform">
...
...
#DELETED THIS > <button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
#ADDED THIS > EKLE
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
} else {
document.subform.submit(); #ADDED THIS PART
}
});
}
</script>

On click bind to form child button

I have a simple form and I am trying to apply my custom function it like this:
$(document).ready(function(){
$("#async_form").asyncpost(defaultAjaxCallback);
});
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(){
event.preventDefault();
$.post(url, data, callback);
});
}
I want to dynamically get the children.btn of form and detect on click on that. This is working but the problem is that where ever on form i click the click is fired. What am I missing here?
The immediate problem is that $.on takes a string in its selector parameter, not a jQuery object. You'll also need to pass event into your click handler, and get the serialized form data in the click handler instead of the ready handler.
$(document).ready(function () {
$("#async_form").asyncpost(null);
});
$.fn.asyncpost = function (callback) {
var url = $(this).attr('action');
$(this).on('click', 'input[type=submit]', event => {
event.preventDefault();
var data = $(this).serialize();
console.log(url, data, callback);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="async_form" action="post.php" method="POST">
<input name="text">
<input name="checkbox" type="checkbox">
<input type="submit">
</form>
Check for current target and target property of event.
e.currentTarget will return element on which you have clicked.
e.target will return element to which the event is attached.
The idea is to check that current target should not be equal to target of event.
Your code will be modified to :-
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(e){
if(e.currentTarget != e.target){
event.preventDefault();
$.post(url, data, callback);
}
});
}
You can also do this way :-
$(this).on('click', 'input[type=submit]', function(e){
event.preventDefault();
$.post(url, data, callback);
});
var btn = $("#frm").children('input[type=submit]');
$("#frm").on("click",btn,function(e){
if(e.currentTarget != e.target){
e.preventDefault();
console.log(e.target);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frm">
<input type="submit"/>
</form>

Call Custom Function on Form Submit

I have a function to swap data-attribute and action in a form:
$(function() {
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
I want to do this upon submission of the form if the form passes validation checks. The validation JS looks like so:
var submitcount7303 = 0;
function checkWholeForm7303(theForm) {
var why = "";
if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
if (why != "") {
alert(why);
return false;
}
if (submitcount7303 == 0) {
submitcount7303++;
SwapAction(); //Calling Function
theForm.submit();
return false;
} else {
alert("Form submission is in progress.");
return false;
}
}
The form doesn't submit and I receive an error:
Reference Error: SwapAction is not defined.
Here is the form HTML with the action:
<form action="" data-action="/FormProcessv2.aspx?WebFormID=89926&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}" enctype="multipart/form-data" onsubmit="return checkWholeForm7303(this)" method="post" name="catwebformform7303" class="review-form custom">
I assume I am overlooking something simple. If I remove SwapAction(); and remove the data-action and set the form back to default it works without a problem.
How do I fix the error and implement my script?
The function is not in scope, it's within the scope of the wrapping DOM ready function, so remove that :
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
You define SwapAction() in the callback function of document ready, that's a different scope, so you can't access it in global scope.
SwapAction() is out of scope here.
If you want to use your first approach:
$(function() {
SwapAction = function {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
And then you can call it as you are calling in your current code.

CKEDITOR: get data from multiple instance names in Javascript

Because I have multiple textareas in HTML code, I pass the id value through Javascript to retrieve the data in each textareas. However, in the JS function, the "CKEDITOR.instances.id" doesn't represent as expected such as CKEDITOR.instances.editor_1, CKEDITOR.instances.editor_2, or CKEDITOR.instances.editor_4, therefore, I don't have any data retrieved. Anyone knows how to fix this please let me. Heaps of thanks.
HTML code:
<textarea name="edit_1"></textarea>
<input type="button" value="submit" onClick="getValue('edit_1')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_2')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_3')" />
JS code:
var getValue = function(id) {
var content = CKEDITOR.instances.id.getData();
alert(content);
};
Try adding [] between id
var getValue = function(id) {
var content = CKEDITOR.instances[id].getData();
alert(content);
};
i had to do something like this as i was binding events to actions with multiple instances.
and trying to get the data but it would always return null for any one but the last... using the event (e.editor) worked though.
var editors = CKEDITOR.instances;
for (var x in editors) {
if (editors[x]) {
var thisName = editors[x].name;
if (editors[thisName]) {
editors[thisName].on('focus', function (e) {
socket.emit('ckeditor_field_type_edit', user, e.editor.name);
});
editors[thisName].on('key', function (e) {
var data = e.editor.getData();
socket.emit('ckeditor_field_type_typing', user, e.editor.name, data);
});
editors[thisName].on('blur', function (e) {
var data = e.editor.getData();
setTimeout(function () {
socket.emit('ckeditor_field_type_edit_finish', user, e.editor.name, data);
}, 1000);
});
}
}
}

JQuery-Submit Form with Var

Hello I have a var in a function when I hit submit...I want to pass the var"fieldNames" to my form....
$(document).ready(function() {
$("#submit").click(function() {
$("#sortable").each(function() {
var fieldNames = $(this).sortable('toArray').toString();
});
$("#detColumnSortorder").submit;
});
});
I want to pass this in my form: fieldNames
Put in a hidden input field in your form. Then set the value on the hidden field. That way when the form submits, the value in the hidden field will be submitted.
HTML:
<input type="hidden" name="fieldNames" value="" />
jQuery:
$(document).ready(function() {
$("#submit").click(function() {
$("#sortable").each(function() {
var fieldNames = $(this).sortable('toArray').toString();
$('input[name=fieldNames]').val(fieldNames);
});
$("#detColumnSortorder").submit;
});

Categories