JavaScript all possible characters after string - javascript

I'm writing a script for a website I'm currently building.
var ownerForm = $('#item_owner_form_');
ownerForm.submit(function(ev) {
//$.ajax({
//'url': 'checklist_changeowner.php',
//'type': 'GET',
//'dataType': 'json',
//'data': {owner: blabla, item: blablbalba, checklist: blabla},
//'success': function() {
//
//}
//});
alert(ownerForm.serialize());
ev.preventDefault();
});
As you've probably already seen, I've set a fixed id for the ownerform (in this case #item_owner_form_) However, I am creating lots of forms through PHP and this is not what I'm looking for. For example, a form that will be generated could be identified as #item_owner_form_42 or as #item_owner_form_913.
Is there a universal character to make sure the ownerForm variable will use all of the forms that start with #item_owner_form_ ? Help would be much appreciated!

You class for that. It can be common for many(similar) elements.
So, your all forms would look like this,
<form id="item_owner_form_1" class="commonItemForm">
</form>
<form id="item_owner_form_2" class="commonItemForm">
</form>
And use the class in jQuery like this,
$('.commonItemForm').submit(function(ev) {
alert($(this).serialize());
ev.preventDefault();
// This function will get triggered for every form which has commonItemForm class.
});

Related

Trying to use an id from the same page that my .click function was triggered on, in an ajax function

newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically

Changing YUI (or AlloyUI) method behaviour

I was trying to change _onFormReset method in YUI (or Alloy UI) - I think it is common JavaScript (OOP) thing, but I am a noob in JS OOP and YUI (been using some JQuery till now) - how can I change functionality of method (keeping other methods as they are)?
for example;
Currently method looks like:
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
},
(src: http://alloyui.com/api/files/alloy-ui_src_aui-form-validator_js_aui-form-validator.js.html#l1192)
But I want it to be like:
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
/* PSEUDO:
**a.) action is logged (ajax call to DB)
b.) all fields in form are reset (default behaviour) + form get's a new anti CSFR UID via ajax
c.) notification is shown (like that message in my example but let's say: Form reseted!)
d.) (Submit button reappears)**
...
*/
},
I tried something like:
/* trying to hijack thingZ */
var FormReset = Y.Component.create({
// component name
NAME : 'form-validator-reset',
EXTENDS : Y.Base,
// Base component's method which extends
prototype : {
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
Y.one("#submitit").setHTML("<h4>Thanks, form submitted ok</h4>");
}
}
});
But with no success.
I looked at documentation and wasn't able to find a way, also it seems like I am missing OOP Javascript basics :(
Can somebody help me "catch the fish" :)
Trying to learn good (OOP) JavaScript for a long time, reading a lot online, but best way for me is learning by coding and now I am really stuck...
So my wish is to have something that I can use in all my forms for when reset button is clicked (in same way I would also change Submit) - OOP method - attached to default reset function, upgrading it in "my" way.
It looks like you're trying to tackle this the wrong way. Unless you're just doing this as an exercise in overriding a method you really shouldn't do that if all you're trying to do is print out a thank you.
Also if you're looking to thank the user for submitting you should be trying to do that when the user submits the form, not when the form is reset. To do this you'd subscribe a function to the 'submit' event of the form.
A.one("#my_form").on("submit", function() {
Y.one("#submitit").setHTML("<h4>Thanks, form submitted ok</h4>");
});
Ok, after rethinking it, I suppose preventDefault is ok for me (I will try to learn OOP JS with other cases :)).
This is (a n00by) solution:
add #resetit to reset button
add code:
var ressetterr = Y.one("#resetit");
Y.one(ressetterr).on("click", function(e){
console.log("resetit");
e.preventDefault();
});

Getting all values being sent to the server at once

I have a form, bunch of inputs and submit button. Some of the inputs are added and deleted dynamically. And some of them may be (or may not) disabled but I still need to get their values of the server.
So I have to add a handler to the button and collect the values of the disabled inputs manually and add them up to other, enabled. inputs. But I'd like not to go that way as it seems too complex (since some of the inputs are added / removed dynamically).
I can also add hidden inputs for each inputs which can be disabled but still it's a bit complex.
What I want is similar to 1. But instead of manually enumerating the enabled inputs by jquery selectors, I want to just get all values are being sent to the server at once by some jquery function maybe or by any other way. And then manually (by selectors) add up the values from the disabled inputs to them. Is this possible?
You could use the jQuery .serialize() for that.
The general structure of the function would look something like this
var mydata = $("#myform").serialize();
$.ajax({
type: "POST",
url: "ajaxurl",
data: mydata,
dataType: "json",
success: function(data) {
...
}
});
So I just figured you had a problem of how to get the disabled fields as well. You could use the function suggested in this thread:
Disabled fields not picked up by serializeArray
Just to make the answer complete, I will copy the plugin from there.
The usage is like this:
var data = $('form').serializeAllArray();
And here's the plugin itself:
(function ($) {
$.fn.serializeAllArray = function () {
var obj = {};
$('input',this).each(function () {
obj[this.name] = $(this).val();
});
return $.param(obj);
}
})(jQuery);
You could use a strategy like the following in your submit handler:
Select all disabled elements .. (don't lose the reference to these)
Enable all disabled elements
Serialize the form .. to get all the data
Disable the elements back
Submit your form.

JQuery: Reusing submit function

Hey guys i have looked as much as i could and i could not find an answer, i am creating an admin interface that has forms all over the place and i would like to use the same jquery code for all of them, i have some code that is getting the job done but i would like to know if there is a more efficient way to do it. here is the code
function submitForm( formname )
{
$.ajax
({
type:'POST',
url: 'session.php',
data: $(formname).serialize(),
success: function(response)
{
if( $('#message_box').is(":visible") )
{
$('#message_box_msg').html ('')
$('#message_box').hide();
}
$('#message_box').slideDown();
$('#message_box_msg').html (response);
}
});
return false;
}
Now my forms look something like this:
<form id="adminForm" action="session.php" method="post" onsubmit="return submitForm('#adminForm');">
Now my question is... is there a simpler way to do this, like without having to provide the submitForm() function with the form id every time?
Thanks in advance!
You may want to delegate a handler to document or other permanent asset in the page(s) to account for any ajax loaded forms. This will replace your inline onsubmit
$(document).on('submit','form', function(){
var allowSubmit=false,
noSubmitMessage="Can't submit", /* can change message in various places in following code depending on app*/
$form=$(this);/* cache jQuery form object */
if( $form.hasClass('doValidation')){
/* class specific code to run*/
allowSubmit = validationFunction();
}
if( allowSubmit){
var data=$form.serialize()
/* do ajax*/
}else{
/* user feedback*/
alert( noSubmitMessage);
}
return false;
});
Yes, define a common class for all your forms, and use
$(".form_class").submit(function() {
//stuff that gets executed on form submission ...
return result;
})
And dump the inline "onsubmit". It's also cleaner to do this in general, as it separated view from behaviour.

Using javascript namespaces with ruby and sinatra

I'm trying to create some javascript validation for my web app and it's all going pretty well except I do not want my script to look for something to validate all the time.
Let's say I have two things I want to validate for but they do not occur on the same page. They are on '/page1' and 'page2' and I don't want my validator for page1 to run on page2.
That should be possible through object literals right?
Something like this:
var validations =
{
page1validation :
{
init : function()
{
// validation page 1
}
}
page2validation :
{
init : function()
{
// validation page 2
}
}
}
So I need to call these validation methods like validations.page1validation.init() and I guess I could do this with inline javascript in each haml view where I have a form that needs validation.
%form{:action => ""}
%input{:type => "text"}
%input{:type => "submit", :value => "save"}
:javascript
$(function() {
validations.page1validation.init();
});
But there must be a better solution - I just can't think of one right now. So what would you do to make sure the validator doesn't try to validate all the time?
Oh and the inline javascript won't work if I put the javascript at the bottom in my layout file...
The simplest way to do what you want is to make the forms different, either with a different id or class.
Then your validations can use that difference to "target" each form independently. You don't need the extra "namespace" with that approach. Instead, you do something like this.
$(function() {
page1validation();
page2validation();
});
function page1validation() {
var form = getElementById('form1'); // form1 is the first form
if(!form) then return;
// .. perform validations in form 1
}
function page2validation() {
var form = getElementById('form2');
if(!form) then return;
// .. perform validations in form 2
}
Also, I'd advice you to invest some time in learning a js library like jQuery. It provides some built-in methods that will make the code above much smaller.

Categories