Jquery to detect if duplicate values in forms - javascript

I have built a dynamic table containing form fields that can be added or removed when required.
What im wondering is.. Is there a plugin or script that has been created that can search a set of form fields for duplicate values ?
Example.
We have a form field with a class of "field-name"
this field may exist 10 times on the page because its part of dynamic rows.
So what im hoping is.. for a plugin that wont allow duplicate values to exist in these fields on the page ?

You can check the fields yourself with a few lines of code. The below runs on form submit and creates a copy of the original values with duplicates removed. If the lists don't match then you know you have some duplicate values.
$('form').submit(function (evt) {
var dynamicFields = $('.field-name'),
uniques = $.unique(dynamicFields);
if (uniques.length != dynamicFields.length) {
alert('Please make sure all your values are unique.');
return false;
}
});

Related

How to navigate to last <input> tag in fieldset using Jquery in a Drupal View form

I am not a front-end developer and I have very limited exposure to JQuery JS etc. So any help is appreciated, thanks.
Objective : - I want to put the sum of all fields (except last ) of a fieldset into last field of that fieldset.
The form is rather complicated, in this form, there are multiple fieldsets and each fieldset contain multiple fields.
This form is generated by Drupal Views & I have very limited options to navigate in this form.
I can not use id, name or any other attribute as they are dynamically generated by CMS also there are hundreds of such fieldset so it is not feasible to write code for every one of them.
So, future addition of fields may alter the attributes. And I can not add my own attributes, classes, or ids to this form.
form looks something like this
<fieldset>
------<div>
---------<fieldset> **this one**
------------------<input>
------------------<input>
------------------<input>
------------------<input>
----------------nth <input> <= Sum of 1st to (n-1)th should come here
-----------------------<div>
I think that it can be done possibly through input:last but can't figure out how to use it properly.
Here is the function I wrote
$(function() {
$('input').change(function() {
var sum = 0;
// Loop through all inputs
$(this).closest('fieldset').find('input').each(function() {
sum += parseInt($(this).val());
console.log(sum);
// i want to put sum into last <input> tag of the current fieldset
});
});
}); // end function()
the output of console.log ($(this).closest('fieldset').find("input").last());); is
So, I figured that I have to extract attribute value, so far I have tried these
$(this).closest('fieldset').find("input").last().data('value'); Undefined
and
$(this).closest('fieldset').find("input").last().attr('value'); results in Undefined

Set multiple form values using jQuery Data attribute

So let us say i have a form with id #form which has two input fields, namely title & price.
I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
the obvious solution that works is
$("#name").val($(this).data('name'));
$("#price").val($(this).data('price'));
This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
Have tried this many ways with no success
Any help is appreciated
You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below
$.fn.applyData = function(form) {
$form = $(form);
$.each($(this).data(), function(i, key) {
$form.find('#' + i).val(key);
});
};
JSFiddle: http://jsfiddle.net/LCM8S/43/

Can CSS or JS effect the submission of a form?

I have a large form spread over 3 tabs. The tabs are controlled by JS which simply changes the css property display: block to display:none depending what tab you click on.
This form also submits data to 3 different tables via php. When i submit my form at the end of the the 3rd tab some of my data is missing in a table that accepts multiple rows (the other two tables only accept a single row) In this section of the form I let the user add as many "Rooms" as they need. The rooms are just a few selection boxes, and the extra selection boxes are also added with JS. When i submit my form only the first "room" is added to the table.
I am positive every thing is working as if I remove the tabs it works perfectly or even if i add all three sections of the form to one tab it works. Below is the PHP that inputs the rooms and loops depending how many there are. Sorry this is a very large form so i dont want to just stick it all in, but it is all very simple and all working. Please let me know if I should add any other part of my code if that helps.
$level = $_POST['level'];
$room_type = $_POST['room_type'];
$width = $_POST['width'];
$length = $_POST['length'];
$num_rooms = count($level);
for($x=0;$x<$num_rooms;$x++)
{
$room_insert = mysqli_query($dbcon, "INSERT INTO listing_rooms (Listing_ID, Level, Type, Length, Width) VALUES ('$listing_id', '$level[$x]', '$room_type[$x]', '$length[$x]', '$width[$x]')") or die(mysql_error());
}
To trigger this I have an if(isset()) just above this. Thanks for any help.
This is the JS that shows and hides the tabs...
function showHideTab(tab_id) {
if (tab_id == 'details_tab'){
document.getElementById('listing_details').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('photo_upload').style.display='none';
}else if (tab_id == 'info_tab') {
document.getElementById('listing_info').style.display='block';
document.getElementById('listing_details').style.display='none';
document.getElementById('photo_upload').style.display='none';
}
else if (tab_id == 'upload_tab') {
document.getElementById('photo_upload').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('listing_details').style.display='none';
}
}
As I thought this was a very simple error. As i said I have 3 divs being shown or hidden by JS. My issue was I had my opening FORM tag inside my first div!
I still dont know why everything other then the array of "rooms" worked fine regardless of where the opening form tag was, and even the array held the first value?

Creating Clones of Forms using jQuery

using jQuery, how can you create a clone of a form without modifying the original form when a different value is selected in the clone. Currently, when selecting a value in the cloned form, the results that is returned is added to the results of the clone, as well as the original. I only want to results to appear for each unique form. Here is what i have:
<script>
$(document).ready(function() {
shows / hides results based on selection
$(".color-select").live("change" ,function(){
if($(this).val() == 'red'){
$('.red').removeClass('hide');
// toggles sub menus
$(this).parent('.controls').find('.submenu-select').removeClass('hide');
}
if($(this).val() == 'orange'){
$('.orange').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
if($(this).val() == 'yellow'){
$('.yellow').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
if($(this).val() == 'green'){
$('.green').removeClass('hide');
$(this).parent('.controls').find('.submenu-select').addClass('hide');
}
});
;
// Duplicates category select menu
$(".add-color").click(function(){
$(".color-category").clone().removeClass('color-category').appendTo("#we-want-to").find('.submenu-select').addClass('hide');
});
$(".add-color-alternate").click(function(){
$(".color-category-alternate").clone().removeClass('color-category-alternate').appendTo("#we-want-to").find('.submenu-select, .results-table').addClass('hide');
});
Heres a fiddle with some html http://jsfiddle.net/mckenney42south/Z4yFs/
Thanks!
The reason you're seeing dickiness between your form's original and cloned instances are twofold:
A form relies on the name attribute for correct submission. In some circumstances, submitting a form with duplicate-named fields will result in an array being sent to the server; in other cases it will overwrite.
Without seeing the rest of your form - the fiddle isn't particularly helpful, sorry - it looks to me like your jQuery selectors are likely returning elements from the clone as well. To combat this, you might give each instance of the form a unique ID and chain your form-altering logic from its own $('#form-n') object, where "n" is to be replaced with the sequential ID number of your form.

Dynamically added JavaScript not finding dynamically added fields in IE

I have a table which has a button to "Add Rows". This button adds a row dynamically with JQuery. It works by copying the first ... and then replacing all the id=".." with an incremented number.
The problem is that the rows have a YUI AutoComplete which looks like the following:
<td>
<input type="hidden" name="location_num[0]" value="508318" maxLength="25" style="width:230px" id="location_num[0]"/>
<input type="textbox" name="location_numDisplayDesc[0]" value="WINNIPEG" maxLength="25" style="width:230px" id="location_numDisplayDesc[0]"/>
<div id="Container_location_num[0]" style="display:inline;"></div>
<script type="text/javascript">
// Initialize autocomplete
var location_numAC = new YAHOO.widget.AutoComplete(
"location_numDisplayDesc[0]",
"Container_location_num[0]",
locationDataSource,
acConfig);
location_numAC.useShadow = true
location_numAC.useIFrame = true
location_numAC.dataErrorEvent.subscribe(acErrorFunction);
// Format results to include the reference number
location_numAC.formatResult = function(resultItem, query) {
return resultItem[0];
};
// Clear key before request
location_numAC.dataRequestEvent.subscribe(function fnCallback(e, args) {
YAHOO.util.Dom.get("location_num[0]").value = ""; });
// Set key on item select
location_numAC.itemSelectEvent.subscribe(function(event, args) {
YAHOO.util.Dom.get("location_num[0]").value = args[2][1];
});
// Clear key when description is cleared
location_numAC.textboxBlurEvent.subscribe(function fnCallback(e, args) {
if (isEmpty(YAHOO.util.Dom.get("location_numDisplayDesc[0]").value)) {
YAHOO.util.Dom.get("location_num[0]").value = "";
} // end if
});
</script>
</td>
This code works fine in Firefox and the newly created AutoCompletes work, but in IE (6 & 7) I am getting an error that means that the location_num_AC is not being created successfully. I believe that it's because that it's not reading the newly created inputs or div as it should. I've tried wrapping the javascript with
$("Container_location_num[0]").ready(function {...});
but that didn't seem to work. Does anyone have any other ideas?
Form fields that are inserted into the DOM in IE don't add to the forms collection as you might expect.
Normally you can refer to a form field one of two ways:
document.forms[0]["myFormName"];
document.forms[0][12];
That is, by its form field name or by its index. But when you add a form field to the DOM in IE you can't refer to it by name, only by its index. If your code (or any supporting code) is looking for a form field in the collection by its name you've obviously got a problem.
If your only key is the name you can loop through all the form fields by index and find what you're looking for, but that's obviously going to be a linear operation. You can also loop through and find which form fields are indexed numerically but not by name and update the form object yourself.
I don't have enough detail to know how (or if) this is occurring in your project, but it's one of those IE quirks that sounds like it might be playing a role since you're adding fields dynamically.

Categories