I have multiple pages across a project I am working on that use AJAX to submit a form to django. All of these buttons work on seemingly everything (mobile and desktop, chrome, firefox, desktop safari) except for mobile safari. Using safari on an iPhone, some of the requests will work, but others won't and I can't seem to figure out why. I have tried to make them all in a similar structure to the one that works, but still, nothing so I figured I'd ask for some help. Thank you in advance!
Here is a working example:
Javascript:
$('#submit').on('click',function(){
dataDict = {csrfmiddlewaretoken:'{{ csrf_token }}'};
dataDict['deleted_exercises'] = deleted_exercises;
var errors = 0;
$('.error').hide();
dataDict['workout_id'] = '{{ workout.id }}';
var exist_exercise_list = [];
$('.existing').each(function(){
//add either new or existing exercise name to exercise list
var ex_name = $(this).find('.ex-name').data('name');
var edit_ex_name_input = $(this).find('.ex-name-input').val();
var ex_name_lower = ex_name.replace(/\s+/g, '-').toLowerCase();
exist_exercise_list.push(ex_name);
var edit_ex_name = ex_name_lower + '-name';
dataDict[edit_ex_name] = edit_ex_name_input;
//add exercise unit to data dict
var edit_ex_unit = $(this).find('.ex-unit').val();
var ex_unit_name = ex_name_lower + '-unit';
dataDict[ex_unit_name] = edit_ex_unit;
//add max event for exercise to data dict
var max_event = $(this).find('.max-event-select').val();
var max_event_name = ex_name_lower + '-max-event';
dataDict[max_event_name] = max_event;
//add color group to data dict
var color_group = $(this).find('.ex-color-select').val();
var color_group_name = ex_name_lower + '-color';
dataDict[color_group_name] = color_group;
//add exercise order to dataDict
var exercise_order = $(this).data('order');
var order_name = ex_name_lower + '-order';
dataDict[order_name] = exercise_order;
//add exercise notes
var notes = $(this).find('.ex-notes').val();
var notes_name = ex_name_lower + '-notes';
dataDict[notes_name] = notes;
//
var sets = $(this).find('.exist-set');
var num_sets = $(sets).length;
var num_sets_name = ex_name_lower + '-num-sets';
dataDict[num_sets_name] = num_sets;
$(sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
//add target weight for this set to dataDict
var target_weight = $(this).find('.weight').val();
if (target_weight != '' && Math.round(target_weight) !== parseInt(target_weight)){
errors = errors + 1;
$(this).find('.weight').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var target_weight_name = ex_name_lower + '-set-' + set_num + '-weight';
dataDict[target_weight_name] = target_weight;
//add max percentage to dataDict
var max_percent = $(this).find('.percentage').val();
if (max_percent != '' && isNaN(max_percent)){
errors = errors + 1;
$(this).find('.percentage').before("<span class='error' style='color: #FF4444'>Please enter a valid percent</span>");
}
var max_percent_name = ex_name_lower + '-set-' + set_num + '-percent';
dataDict[max_percent_name] = max_percent;
//add reps to dataDict
var reps = $(this).find('.reps').val();
if (reps != '' && Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var reps_name = ex_name_lower + '-set-' + set_num + '-reps';
dataDict[reps_name] = reps;
})
var added_sets_list = [];
var added_sets = $(this).find('.new-set');
$(added_sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
var target_weight = $(this).find('.target-weight-input').val();
if (target_weight != '' && Math.round(target_weight) !== parseInt(target_weight)){
errors = errors + 1;
$(this).find('.target-weight-input').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var max_percent = $(this).find('.max-percent').val();
if (max_percent != '' && isNaN(max_percent)){
errors = errors + 1;
$(this).find('.max-percent').before("<span class='error' style='color: #FF4444'>Please enter a valid percent</span>")
}
var reps = $(this).find('.reps').val();
if (reps == '' || Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var add_set = set_num + '_-&&-_' + target_weight + '_-&&-_' + max_percent + '_-&&-_' + reps;
added_sets_list.push(add_set);
})
var added_sets_name = ex_name_lower + '-added-sets';
dataDict[added_sets_name] = added_sets_list;
})
var new_exercises = [];
$('.new-ex').each(function(){
var new_ex_name = $(this).find('.new-ex-name').val();
if (new_ex_name == ''){
errors = errors + 1;
$(this).find('.new-ex-name').before("<span class='error' style='color: #FF4444'>Please enter an exercise name</span>")
}
new_exercises.push(new_ex_name);
var new_ex_name_lower = new_ex_name.replace(/\s+/g, '-').toLowerCase();
var new_ex_order = $(this).data('order');
var new_ex_order_name = new_ex_name_lower + '-order-new';
dataDict[new_ex_order_name] = new_ex_order;
var new_ex_unit = $(this).find('.new-ex-unit').val();
var new_ex_unit_name = new_ex_name_lower + '-unit-new';
dataDict[new_ex_unit_name] = new_ex_unit;
var new_ex_max_event = $(this).find('.new-ex-max-event').val();
var new_ex_max_event_name = new_ex_name_lower + '-max-event-new';
dataDict[new_ex_max_event_name] = new_ex_max_event;
var new_ex_color = $(this).find('.new-ex-color-select').val();
var new_ex_color_name = new_ex_name_lower + '-color-new';
dataDict[new_ex_color_name] = new_ex_color;
var new_ex_notes = $(this).find('.new-ex-notes').val();
var new_ex_notes_name = new_ex_name_lower + '-notes-new';
dataDict[new_ex_notes_name] = new_ex_notes;
var new_ex_sets = $(this).find('.set');
var num_set_new = $(new_ex_sets).length;
var num_set_new_name = new_ex_name_lower + '-num-sets-new';
dataDict[num_set_new_name] = num_set_new;
$(new_ex_sets).each(function(){
var set_num = $(this).find('.set-num').data('number');
var weight = $(this).find('.target-weight-input').val();
if (weight != '' && Math.round(weight) !== parseInt(weight)){
errors = errors + 1;
$(this).find('.target-weight-input').before("<span class='error' style='color: #FF4444'>Please enter a valid weight</span>");
}
var weight_name = new_ex_name_lower + '-set-' + set_num + '-weight-new';
dataDict[weight_name] = weight;
var percent = $(this).find('.max-percent').val();
if (percent != '' && isNaN(percent)){
errors = errors + 1;
$(this).find('.max-percent').before("<span class='error' style='color: #FF4444'>Please enter a valid percentage</span>");
}
var percent_name = new_ex_name_lower + '-set-' + set_num + '-percent-new';
dataDict[percent_name] = percent;
var reps = $(this).find('.reps').val();
if (reps == '' || Math.round(reps) !== parseInt(reps)){
errors = errors + 1;
$(this).find('.reps').before("<span class='error' style='color: #FF4444'>Please enter a valid rep number</span>");
}
var reps_name = new_ex_name_lower + '-set-' + set_num + '-reps-new';
dataDict[reps_name] = reps;
})
})
dataDict['removed_sets'] = removed_sets;
dataDict['deleted_exercises'] = deleted_exercises;
dataDict['existing_exercises'] = exist_exercise_list;
dataDict['new_exercises'] = new_exercises;
if (errors == 0){
$.ajax({
url: "/edit_athlete_workout/",
type: 'POST',
data: dataDict,
success : function() {
window.location.reload(true);
},
error : function(xhr,errmsg,err) {
$('#result').append("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
})
Button:
<button class='btn' id='submit' type='button'>Submit</button>
And one that doesn't work:
$('#complete-wo').on('click',function(){
event.preventDefault();
results = {csrfmiddlewaretoken:'{{ csrf_token }}'};
$('.errorDesc').remove();
var ex_ids = [];
var errors = 0;
results['exercises'] = ex_ids;
$('.ex-id').each(function(i, obj){
var exercise_id = $(obj).val()
ex_ids.push(exercise_id);
var reps_comp = $('input[name="reps-ex-'+ exercise_id + '"').val();
if (reps_comp == '' || Math.round(reps_comp) !== parseInt(reps_comp)){
errors = errors + 1;
$('input[name="reps-ex-'+ exercise_id + '"').before('<div class="errorDesc" style="color: #FF0000"> Enter a valid rep number</div>');
}
var load_comp = $('input[name="load-ex-'+ exercise_id + '"').val();
if (load_comp == '' || Math.round(load_comp) !== parseInt(load_comp)){
errors = errors + 1;
$('input[name="load-ex-'+ exercise_id + '"').before('<div class="errorDesc" style="color: #FF0000"> Enter a valid weight</div>');
}
results['reps-ex-' + exercise_id] = reps_comp;
results['load-ex-' + exercise_id] = load_comp;
//alert(exercise_id + '/' + results['reps-ex-' + exercise_id] + results['load-ex-' + exercise_id]);
})
if (errors == 0){
$.ajax({
url: "/submit_workout/",
type: 'POST',
data: results,
success : function() {
window.location.href = '/player_calendar/';
},
error : function(xhr,errmsg,err) {
$('#result').append("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
});
Button:
<button class='btn btn-primary btn-block' id='complete-wo' type='button'>Workout Complete</button>
I found a solution to this problem. For some reason, on mobile safari, there was a problem with selecting the inputs using:
var reps_comp = $('input[name="reps-ex-'+ exercise_id + '"').val();
load_comp = $('input[name="load-ex-'+ exercise_id + '"').val();
The page worked fine once I switched these to just be class-based selectors.
Related
This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>
This question already has answers here:
Test if something is not undefined in JavaScript
(11 answers)
Closed 6 years ago.
I get this error so my update button doesnt work and I havent updated my database progress because of this error.I want to be visible of textbox and I try to do in .cs side
This javascript codes using checkboxs and textboxs send to cs side with json
function UpdateDetails1() {
var bEnabled = GetCheckBoxVal($("#<%=CB_Enabled_Edit.ClientID%>"));
var bDisplayDetails = GetCheckBoxVal($("#<%=CB_DisplayDetails_Edit.ClientID%>"));
var b3rdParty = GetCheckBoxVal($("#<%=CB_b3rdParty_Edit.ClientID%>"));
var bDisplayOpenNow = GetCheckBoxVal($("#<%=CB_DisplayOpenNow_Edit.ClientID%>"));
var bReservation = GetCheckBoxVal($("#<%=CB_Reservation_Edit.ClientID%>"));
var bPromotion = GetCheckBoxVal($("#<%=CB_Promotion_Edit.ClientID%>"));
var bOnlyPromotion = GetCheckBoxVal($("#<%=CB_OnlyPromotion_Edit.ClientID%>"));
var bAllowFollow = GetCheckBoxVal($("#<%=CB_AllowFollow_Edit.ClientID%>"));
var bAlacarte = GetCheckBoxVal($("#<%=CB_Alacarte_Edit.ClientID%>"));
var bDisplayOpenEat = GetCheckBoxVal($("#<%=CB_DisplayOpenEat_Edit.ClientID%>"));
var Coord_Lat = $("#<%=TB_Coord_Lat_Edit.ClientID%>")[0].value;
var Coord_Long = $("#<%=TB_Coord_Long_Edit.ClientID%>")[0].value;
var Price = $("#<%=TB_Price_Edit.ClientID%>")[0].value;
alert(Price);
var Phone_Number = $('#<%=TB_Phone_Number_Edit.ClientID%>')[0].value;
if (bReservation == true)
$("#display_res_schedule").css("display", "block");
else
$("#display_res_schedule").css("display", "none");
var jsonData = '{ bEnabled: "' + bEnabled + '",' +
'bDisplayDetails: "' + bDisplayDetails + '",' +
'b3rdParty: "' + b3rdParty + '",' +
'Price: "' + Price + '",' +
'bDisplayOpenNow: "' + bDisplayOpenNow + '",' +
'bReservation: "' + bReservation + '",' +
'bPromotion: "' + bPromotion + '",' +
'Phone_Number: "' + Phone_Number + '",' +
'bOnlyPromotion: "' + bOnlyPromotion + '",' +
'bAllowFollow: "' + bAllowFollow + '",' +
'bAlacarte: "' + bAlacarte + '",' +
'bDisplayOpenEat: "' + bDisplayOpenEat + '",' +
'Coord_Lat: "' + Coord_Lat + '",' +
'Coord_Long: "' + Coord_Long + '" }';
alert(jsonData);
// var jsonData = '{ bEnabled: "' + bEnabled + '",' +
// 'bDisplayOpenNow: "' + bDisplayOpenNow + '",' +
// 'bReservation: "' + bReservation + '",' +
// 'Coord_Lat: "' + Coord_Lat + '",' +
// 'Coord_Long: "' + Coord_Long + '" }';
$.ajax({
type: "POST",
url: "Edit.aspx/UpdateDetails1",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: GetDetails1,
failure: function (response) {
alert(response.d);
}
});
}
I need to do visible false checkboxes and textboxes that I don't use.But TB_Phone_Number_Edit.Visible gets Uncaught TypeError: Cannot read property 'value' of undefined error
protected void Page_Load(object sender, EventArgs e)
{
LoadType = Request.QueryString["t"].ToString();
if (LoadType == "Agency")
{
CB_DisplayOpenNow.Visible = false;
CB_DisplayOpenNow_Edit.Visible = false;
CB_Alacarte.Visible = false;
CB_Alacarte_Edit.Visible = false;
CB_DisplayOpenEat.Visible = false;
CB_DisplayOpenEat_Edit.Visible = false;
CB_Reservation.Visible = false;
CB_Reservation_Edit.Visible = false;
CB_Promotion.Visible = false;
CB_Promotion_Edit.Visible = false;
CB_OnlyPromotion.Visible = false;
CB_OnlyPromotion_Edit.Visible = false;
TB_Price_Edit.Visible = false;
DDL_Currency.Visible = false;
DDL_Camera.Visible = false;
CB_AllowFollow.Visible = false;
CB_AllowFollow_Edit.Visible = false;
WhatDoNow.Visible = false;
Alacarte.Visible = false;
WhatEatNow.Visible = false;
Promotion.Visible = false;
Reservation.Visible = false;
OnlyPromotion.Visible = false;
Price.Visible = false;
Camera.Visible = false;
AllowFollow.Visible = false;
Label23.Visible = false;
Label24.Visible = false;
Label25.Visible = false;
Label26.Visible = false;
Label27.Visible = false;
Label29.Visible = false;
Label30.Visible = false;
Label33.Visible = false;
Label34.Visible = false;
TB_Price_Edit.Visible = false;
}
else if(LoadType == "Tour"){
CB_b3rdParty.Visible = false;
CB_b3rdParty_Edit.Visible = false;
CB_Alacarte.Visible = false;
CB_Alacarte_Edit.Visible = false;
DDL_Camera.Visible = false;
CB_AllowFollow.Visible = false;
CB_AllowFollow_Edit.Visible = false;
CB_DisplayOpenEat.Visible = false;
CB_DisplayOpenEat_Edit.Visible = false;
b3rdParty.Visible = false;
Alacarte.Visible = false;
WhatEatNow.Visible = false;
Camera.Visible = false;
AllowFollow.Visible = false;
Label18.Visible = false;
Label24.Visible = false;
Label25.Visible = false;
Label33.Visible = false;
Label34.Visible = false;
Phone_Number.Visible = false;
TB_Phone_Number_Edit.Visible = false;
Label8.Enabled = false;
}
Assuming the problem is not in GetCheckBoxVal any of the following statements is causing your issue:
var Coord_Lat = $("#<%=TB_Coord_Lat_Edit.ClientID%>")[0].value;
var Coord_Long = $("#<%=TB_Coord_Long_Edit.ClientID%>")[0].value;
var Price = $("#<%=TB_Price_Edit.ClientID%>")[0].value;
var Phone_Number = $('#<%=TB_Phone_Number_Edit.ClientID%>')[0].value;
Why? Because if the css selector given to jQuery returns no matches, the array will have zero elements, aka, its length will be 0. That does mean that even on element[0] there is nothing, its value is undefined. Trying to get a property or invoke a method on an undefined value gives you the exception you see.
As the suggested duplicate suggest you should guard against this situation. One possible way is to introduce a utility function:
// this gets the value property of an object and if object is undefined
// returns a default
function getValueOrDefault(someObject, reasonableDefault) {
return someObject === undefined ? reasonableDefault : someObject.value;
}
// your original function
function UpdateDetails1() {
// rest of your code
}
With that function in place your code becomes:
var Coord_Lat = getValueOrDefault($("#<%=TB_Coord_Lat_Edit.ClientID%>")[0], '0.0');
var Coord_Long = getValueOrDefault($("#<%=TB_Coord_Long_Edit.ClientID%>")[0], '0.0');
var Price = getValueOrDefault($("#<%=TB_Price_Edit.ClientID%>")[0],0);
var Phone_Number = getValueOrDefault($('#<%=TB_Phone_Number_Edit.ClientID%>')[0],'+1 010');
That should resolve the Uncaught type error. It is up to you to come up with reasonable defaults.
Setting a textbox to Visible = false makes it not render in your html. So when you try to get the value in your javascript, it effectively does not exist, making it undefined.
To fix this, either replace the textbox by a hidden field or change the opacity so that the textbox is there but transparent.
I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...
I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}
In my JavaScript program, I get values from a form through its elements and then print them in order, in an alert. This works fine in Firefox, but in Chrome the order is wacky and it ends with the "Submit" button.
I tried getting rid of the fieldset and adjusting the numbers, and it worked, but I liked the fieldset! Also, I can't just make an array and iterate through it because the fields are tab-order adjusted and I want to print them accordingly. Any suggestions?
Upon trying to validate I found that I do indeed need the fieldset for XHTML Strict. I've been storing the elements in an array, like so:
var $ = function (id) { return document.getElementById(id); }
function check() {
var x = $("myForm");
var user = new Array();
user[0] = x.elements[0].value;
user[1] = x.elements[2].value;
user[2] = x.elements[4].value;
user[3] = x.elements[1].value;
user[4] = x.elements[3].value;
user[5] = x.elements[5].value;
And then checking them using another couple of arrays and displaying the results in a pop-up:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
if (user[i] == "") {
display[i] = "You entered nothing.";
}
else if (user[i] == answers[i]) {
display[i] = "Correct!";
}
else {
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
}
WebKit bug (https://bugs.webkit.org/show_bug.cgi?id=48193).
I think you'll be better off using IDs:
<form ...>
<input ... id="q0" />
<input ... id="q1" />
<input ... id="q2" />
</form>
So you can write this JavaScript code:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display[i] = "You entered nothing.";
else if (user == answers[i])
display[i] = "Correct!";
else
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
Your code can receive a lot of improvement, too:
var answers = [ "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" ];
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display.push( "You entered nothing." );
else if (user == answers[i])
display.push( "Correct!" );
else
display.push ( "Wrong. The correct answer is \"" + answers[i] + "\"." );
}
alert(display.join('\n'));