Dynamically added JavaScript not finding dynamically added fields in IE - javascript

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.

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

Overriding difficult view model

I am trying to replace some text in an input field using JS but the view model overrides my commands each time. This is the HTML I start with:
<td class="new-variants-table__cell" define="{ editVariantPrice: new Shopify.EditVariantPrice(this) }" context="editVariantPrice" style="height: auto;">
<input type="hidden" name="product[variants][][price]" id="product_variants__price" value="25.00" bind="price" data-dirty-trigger="true">
<input class="mock-edit-on-hover tr js-no-dirty js-variant-price variant-table-input--numeric" bind-event-focus="onFocus(this)" bind-event-blur="onBlur(this)" bind-event-input="onInput(this)">
</td>
I run this JS:
jQuery('#product_variants__price').siblings().removeAttr('bind-event-focus');
jQuery('#product_variants__price').siblings().removeAttr('bind-event-input');
jQuery('#product_variants__price').siblings().removeAttr('bind-event-blur');
jQuery('#product_variants__price').siblings().focus()
jQuery('#product_variants__price').siblings().val("34.00");
jQuery('#product_variants__price').val("34.00");
And I'm left with the following HTML:
<td class="new-variants-table__cell" define="{ editVariantPrice: new Shopify.EditVariantPrice(this) }" context="editVariantPrice" style="height: auto;">
<input type="hidden" name="product[variants][][price]" id="product_variants__price" value="34.00" bind="price" data-dirty-trigger="true">
<input class="mock-edit-on-hover tr js-no-dirty js-variant-price variant-table-input--numeric">
</td>
The problem is that each time I click the input field the value is reverted to what it was when the page loaded.
I've also tried running the command in the parent td along with my value change, to simulate the editing of a variant and preventing default with no success:
jQuery('#product_variants__price').siblings().bind('input', function (e) {
e.preventDefault();
return false;
});
jQuery('#product_variants__price').siblings().bind('focus', function (e) {
e.preventDefault();
return false;
});
jQuery('#product_variants__price').siblings().focus()
jQuery('#product_variants__price').siblings().val("£34.00");
jQuery('#product_variants__price').val("£34.00");
jQuery('#product_variants__price').siblings().keydown()
Parent td function:
new Shopify.EditVariantPrice(jQuery('#product_variants__price').parent())
So how can I successfully edit this value in the inputs and also update the Shopify view model?
You can try this for yourself by going here:
https://jebus333.myshopify.com/admin/products/2521183043
login jebus333#mailinator.com
password shop1
EDIT: I've tried to find the view model on the page but with no success. Plus, there are no network calls when editing the values in the input fields, leading me to believe the values are being pulled back from somewhere on page.
Try this:
var old = Shopify.EditVariantPrice.prototype.onFocus;
Shopify.EditVariantPrice.prototype.onFocus = function(t) {
this.price = '50.00'; // Use the price you want here
old.call(this, t);
};
jQuery('#product_variants__price').siblings().triggerHandler("focus");
jQuery('#product_variants__price').siblings().triggerHandler("blur");
If it works for you, it's possible that the following will be sufficient:
Shopify.EditVariantPrice.prototype.onFocus = function(t) {
this.price = '50.00'; // Use the price you want here
};
Well, there is a kind of a dirty solution...
First of all you'll need a sendkeys plugin. In fact that means you'll need to include this and this JS libraries (you can just copy-paste them in the console to test). If you don't want to use the first library (I personally find it quite big for such a small thing) you can extract only the key things out of it and use only them.
The next step is creating the function which is going to act like a real user:
function input(field, desiredValue) {
// get the currency symbol while value is still pristine
var currency = field.val()[0];
// move focus to the input
field.click().focus();
// remove all symbols from the input. I took 10, but of course you can use value.length instead
for (var i = 0; i < 10; i++) field.sendkeys("{backspace}");
// send the currency key
field.sendkeys(currency);
// send the desired value symbol-by-symbol
for (var i = 0; i < desiredValue.length; i++) field.sendkeys(desiredValue[i]);
}
Then you can simply call it with the value you wish to assign:
input($("#product_variants__price").next(), "123.00");
I did not really manage to fake the blur event because of lack of the time; that is why I was forced to read the currency and pass .00 as a string. Anyway you already have a way to go and a quite working solution.
Looks like you're trying to automate editing of variant prices of products in Shopify's admin panel.
Instead of playing around with the DOM of Shopify's admin page, I'll suggest using Shopify's bulk product editor which lets you set prices of all variants in a single screen. I feel that you'll have better luck setting the variant prices using JavaScript on the bulk product editor page.
Clicking on the 'Edit Products' button as shown in the screenshot below will open the bulk product editor.
Also check if browser based macro recording plugins like iMacro can be of your help (you can also code macros with JS in iMacro).

Repeat a div with javascript?

I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.
this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method
You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.
lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});

Jquery to detect if duplicate values in forms

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;
}
});

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories