I have a custom jQuery script that works fine in all bowsers but one (Explorer 6, 7, 8?).
The purpose of the code is to allow a user to add multiple form fields to their form (if the user want more than one phone number or more than one web address).
It is written so that any "A" tag with a class containing "add" is bound to the jQuery function.
The error I am getting is as follows:
///////////////////////////////
Line: 240
Char: 5
Error: 'this.id.3' is null or not an object
Code: 0
///////////////////////////////
HTML of form:
(please note that I am aware that the form tags are not here, this is a small portion of a larger form.
<ul>
<li>
<ul>
<li class="website">
<input id="website1_input" name="website[1][input]" type="text" value="www.test.org"/>
<input type="checkbox" id="website1_delete" name="website[1][delete]" class="element radio" value="1" />
<label for="website1_delete">Delete</label>
</li>
</ul>
add another website
</li>
</ul>
And now the jQuery:
There should be on a page a ul containing at least one li.
All the lis should have a certain class like "phone" or "address"
After the /ul There should be a link with a matching id, like
"addPhone" or "addAddress". The href attribute should be "#".
function makeAddable(theClass) {
$('#add' + theClass[0].toUpperCase() + theClass.substr(1)).click(function() {
var numItems = $('.' + theClass).length;
var newItem = $('.' + theClass).eq(numItems - 1).clone();
newItem.find('input[type=text]').val('');
numItems++; // number in the new IDs
// keep ids unique, linked to label[for], and update names
// id & for look like: phone1_type, phone1_ext, phone13_p1, etc.
// names look like: phone[1][type], phone[1][ext], phone[13][p1], etc.
newItem.find('[id^=' + theClass + ']').each(function(i) {
var underscoreIndex = this.id.indexOf('_');
var idNum = this.id.substring(theClass.length, underscoreIndex);
this.id = this.id.replace(idNum, numItems);
});
newItem.find('[for^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var forAttr = jqthis.attr('for');
var underscoreIndex = forAttr.indexOf('_');
var idNum = forAttr.substring(theClass.length, underscoreIndex);
forAttr = forAttr.replace(idNum, numItems);
jqthis.attr('for', forAttr);
});
newItem.find('[name^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var nameAttr = jqthis.attr('name');
var bracketIndex = nameAttr.indexOf(']');
var idNum = nameAttr.substring(theClass.length + 1, bracketIndex);
nameAttr = nameAttr.replace(idNum, numItems);
jqthis.attr('name', nameAttr);
});
$(this).prev('ul').append(newItem);
return false;
});
}
// Automatically enable all <a href="#" id="addSomething"> links
$(function() {
$('a[href=#][id^=add]').each(function(i) {
makeAddable( this.id[3].toLowerCase() + this.id.substr(4) );
});
});
this.id.charAt(3).toLowerCase()
Change this...
this.id[3]
To this...
this.id.substr(3, 1);
Something like this will achieve the same affect but makes greater use of jquery, thereby avoiding the crossbrowser compatibility problems so common with javascript:
function addInput(inputType) {
var items, itemNumber, lastItem, newListItem, parentList, inputName, inputId, deleteId, thisId;
items = $('li.' + inputType);
itemNumber = items.length + 1;
lastItem = $(items[itemNumber-2]);
newListItem = lastItem.clone();
parentList = lastItem.parents('ul:first');
inputId = inputType + itemNumber + '_input';
deleteId = inputType + itemNumber + '_delete';
$(':input', newListItem).each(function() {
inputName = $(this).attr('name').replace(/\[\d*\]/, '['+itemNumber+']');
thisId = $(this).attr('id').match(/_delete/) ? deleteId : inputId
$(this)
.val('')
.removeAttr('checked')
.attr('id', thisId)
.attr('name', inputName)
}).end()
.find('label').attr('for', deleteId).end()
.appendTo(parentList)
;
}
$(function() {
$('a[href=#][id^=add]').live('click', function() {
addInput(this.id.substr(3).toLowerCase());
});
});
Related
I try to create a generator for lucky numbers. I did it with C# and now with JavaScript and jQuery. You can see this here. When I add new field - JQ do not see it. Just try to click on numbers in "Your field". I have as standard 7 fields and they work fine but when I add new line script do not recognise it like something useful. Could you give me some advice?
change below js code. check this working plunker
Your code:
$('.spielzahlen').on('click', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
Change it with below code , there is only change in initialization other code are same :
$(document).on('click','.spielzahlen', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
I have a text box. When I click on the listed data (Data is getting from table). I need to set response table row ID in text box.
I need data to set like this "|13456|1400|14567|" in the text box.
Please help me to set id in text box. Currently I can set only one ID.
Please find the attached image
JS
$.post("getDetailsAjax.php", {keywords: keywords}, function(data){
$.each(data, function() {
var leftboxid = this.id;
var producer = this.producer;
var model = this.model;
var typ = this.typ;
var body = this.body;
var date_from = this.date_from;
var date_to = this.date_to;
var power = this.power;
var engine_code = this.engine_code;
var fuel = this.fuel;
var ccm = this.ccm;
var cylinders = this.cylinders;
$('#search-result').append('<div class="leftboxid_'+leftboxid+'" data-leftbox="' +leftboxid+ '"><a href="#" class="list-group-item"><p class="list-group-item-text">' +producer+ ' '+model+' '+typ+' ('+body+')</p><p class="list-group-item-text">' +date_from+ ' to ' +date_to+ '</p> <p class="list-group-item-text">' +power+' ps .' +engine_code+' . ' +fuel+ ' . '+ccm+' ccm . ' +cylinders+ ' cyl</p></div>');
/* right box */
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").attr("value", setID);
});
});
}, "json");
Textbox
<div class="col-xs-4">
<input type="text" class="form-control append-left-id" placeholder="Result Field">
</div>
I think you want this
instead of this code:
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").attr("value", setID);
});
use this :
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").val($(".append-left-id").val()+"|"+setID);
});
You can append like so:
.....
var setID = $(this).attr("data-leftbox");
var val = $(".append-left-id").val();
$(".append-left-id").val(val+"|"+setID );
....
Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});
In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});
How to add a title for the JqueryUI dialog box for this case. This dialog box opens as per the model name in ruby on rails.
Example of the html page:
<%= link_to pro_generic_lookup_data_path("Enr::Rds::Section2009", format: :js), data: {remote: true} %>
Here, the pro_generic_lookup_data is have the option of uidialog box. So, it would open depend upon the model name("Enr::Rds::Section2009").
JavaScript
var generic_lookup_Enr_Rds_Section2009_selected = function(id, to_s) {
var section_value = $(".cross-reference-section-value");
var section_id = $(".cross-reference-section-value-id");
var section_clear_img = $(".cross-reference-section-clear-img");
section_id.val(id);
section_value.text(to_s);
section_value.css('display', 'inline');
section_clear_img.css('display', 'inline');
$(section_clear_img).on('click', function() {
section_value.text('')
section_id.val('')
section_clear_img.css('display', 'none');
});
var question_link = $('#question_picker').attr('href');
question_link = question_link.replace(/\?+$/, '');
question_link = question_link + '?columns[enr_rds_section_id]=' + id;
$('#question_picker').attr('href', question_link);
$("#modal_popup").dialog("destroy");
};
I have three fields like this same. So, I need to give a separate titles for all the three fields. Thanks!
Other than some basic formatting and using chained selectors where applicable, the code is fine.
var generic_lookup_Enr_Rds_Section2009_selected = function(id, to_s) {
var $section_value = $(".cross-reference-section-value");
var $section_id = $(".cross-reference-section-value-id");
var $section_clear_img = $(".cross-reference-section-clear-img");
$section_id.val(id);
$section_value.text(to_s).css('display', 'inline');
$section_clear_img.css('display', 'inline').on('click', function() {
$section_value.text('')
$section_id.val('')
$section_clear_img.css('display', 'none');
});
var question_link = $('#question_picker').attr('href');
question_link = question_link.replace(/\?+$/, '');
question_link = question_link + '?columns[enr_rds_section_id]=' + id;
$('#question_picker').prop('href', question_link);
$("#modal_popup").dialog("destroy");
};