Issue with event delegation - javascript

I am trying to clone a table once the table has been populated. Inside the td I placed some input and textarea tags. The problem that I have is that the contents inside the table are not cloned. I have tried to use event delegation, but it seems that I am doing something wrong.
Here is the JSfiddle, write something inside the table and then press clone.``
http://jsfiddle.net/no84bror/2/
$("#clonetable").on('click','textarea',function(){
var tempTable = $('#masterTable');
var temClone = $("<div/>").append(tempTable.clone()).html();
// alert(temClone);
var rep = temClone.replace("textarea","p");
$("#a").html(rep);
});

This is a jquery bug - deep cloning does not work for textareas http://bugs.jquery.com/ticket/3016
It started as a problem in Firefox but is the same in Chrome, apparently.
"The current behavior is documented at api.jquery.com and of course here. A plugin is available to provide the requested behavior. The ticket is marked patchwelcome, with the caveat that fixing this edge case inside jQuery causes a performance hit for the 90% of the time when it isn't needed."
The following code works and copies the contents of the input field, but due to the above bug you will have to copy the contents of textareas yourself or use the plugin.
$("#clonetable").on('click', function(){
$("#a").html($('#masterTable').clone());
});
you can try using .clone( [withDataAndEvents][, deepWithDataAndEvents] ), in other words using .clone(true, true), but it makes no difference.
Here's the code, including the hack to copy textarea content:
$("#clonetable").on('click',function(){
$("#a").html($('#masterTable').clone());
var my_textareas = $('#masterTable textarea').slice(2,4);
var result_textareas = $("#a textarea");
for (var i = 0, l = my_textareas.length; i < l; ++i){
$(result_textareas[i]).val($(my_textareas[i]).val());
}
});

Related

Web page doesn't behave as though checkboxes are checked after manipulating in the console

Excuse my limited ability to be able to frame the question. I need to check 100 boxes to apply an accounting rule to 100 bank entries (in FreeAgent). In the console in Google Chrome I have typed the following, which succesfully checks the first box in the list. (Once it works I will put it in a loop so it checks all of them but I'm not at that point yet.)
var x = document.getElementsByClassName('FormElement-checkbox');
x[1].firstElementChild.checked = true;
When I try to continue with the procedure, the web page doesn't "realise" that the boxes have been checked. I can only get it to work if I physically click the checkboxes individually on the page - the fact they appear checked doesn't seem to matter to the page. So there is obviously something I am missing.
I can succesfully enter text into boxes and select items in drop downs. I have tried inspecting the checkbox element and seeing what happens when it is checked by clicking on it, but I can't see any difference in the HTML. I have explored a lot of the attributes in the javascript for that object when typing
x;
which is how I found the .firstElementChild.checked = true in the first place.
I don't know whether it is something specific to the page itself or whether in general I don't have enough experience to be able to tackle all data entry situations yet. I have tried searching for answers on this forum and elsewhere.
Have you tried something like this:
var x = document.getElementsByClassName('FormElement-checkbox')
x[0].checked = true;
or use the click() method on checkbox element.
Part of HTML document might be helpful.
This happens most likely because of some JS/CSS trickery - the elements are listening to click event rather than change in HTML property. Try raising .click event
var cbs = document.getElementsByClassName("FormElement-checkbox")
for (var i = 0; i < cbs.length; i++){
cbs[i].click()
}
Try this:
var x = document.getElementsByClassName('FormElement-checkbox');
var result = "document.getElementsByClassName('FormElement-checkbox')";
for (var i=0, len=x.length|0; i<len; i=i+1|0) {
result += "\n " + x[i].textContent;
}
You can also try using:
document.querySelector(".FormElement-checkbox")
to get the first element with the class_name (or)
document.querySelectorAll(".FormElement-checkbox")
to get a list of elements with the class_name
You can find everything about Document.getElementsByClassName() here at this link

Issue in select option in Jquery mobile

I have a table which contains input text and select option and button.The table row is cloned when the button is clicked. Every thing is working fine except the select option. After the table row is cloned the select option not display what i select. Here is the JsFiddle http://jsfiddle.net/aravinth/Ad22d/
Javascript code like
var b = 1;
function cloneRow() {
var row = document.getElementById("table");
var table = document.getElementById("particulars");
var clone = row.rows[1].cloneNode(true);
var clones = row.rows.length;
var workerName = clone.cells[0].getElementsByTagName('input')[0];
var position = clone.cells[2].getElementsByTagName('select')[0];
var date1 = clone.cells[3].getElementsByTagName('input')[0];
var fromHr = clone.cells[4].getElementsByTagName('input')[0];
var toHr = clone.cells[5].getElementsByTagName('input')[0];
var add = clone.cells[1].getElementsByTagName('input')[0];
workerName.id = "workerName" + b;
position.id = "position" + b;
date1.id = "date1" + b;
fromHr.id = "fromHr" + b;
toHr.id = "toHr" + b;
add.id = "add" + b;
$(date1).datebox();
table.appendChild(clone);
b++;
}
Also i referred this
1 . Change Select value using jQuery Uniform.js
2 . jquery cloning a block of element. select element acting weired
3. select not working after .clone
but not get success. Please suggest some solutions.
It seems, jQuery mobile doesn't recognize the cloned selectmenu.
What you can do, is remove the selectmenu and re-add only the HTML select and then initialize it with selectmenu()
$('.ui-select', clone).remove();
clone.cells[2].appendChild(position);
$(position).selectmenu();
See modified JSFiddle
Update:
I just followed jquery cloning a block of element. select element acting weired and found #malko's answer, which is a lot more elegant than removing and reinserting. This reduces it to
$(position).closest('.ui-select').replaceWith(position);
$(position).selectmenu();
See JSFiddle
I think you solved select option issue by using this answer. And another one issue you need to fix in your fiddle. The issue is time picker for last two columns (fromHr and toHr).
To fix this you need to add the bellow lines in your javascript code.
$(fromHr).datebox();
$(toHr).datebox();
because those rows are dynamically created. So you need to add the above lines to show time picker in your fromHr and toHr.
See this working FIDDLE
The issue is that jQuery Mobile recreates a lot of elements, for example your select, to be non-native widgets, and then binds functions to certain events. When you just clone the row, you aren't getting the event-bindings, so what you need to do is actually append the raw html -- what it was before it got re-rendered -- and then trigger the create method:
var template="<tr><td>..your row here..</td></tr>";
$("#particulars").append(template).parent().trigger('create');
I have a barely working fiddle, but I removed a lot of your code so I could easily illustrate what I am talking about.
http://jsfiddle.net/Ad22d/81/
I had the same issue and fixed it by calling selectmenu("destroy") on the original select box before cloning, and then re-initializing select boxes by calling selectmenu() after cloned select is appended.

Difficulty setting focus on newly created object in javascript

So, related to an earlier question, but forgive me for my naive javascript ways. Basically I now want to automatically bring a text input into focus when it is added to the DOM. Part of me thinks that I might be trying to add focus to the object before it exists, but I'm not quite sure how I would go about fixing it. Right now this is my relevant code:
var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
this.parentNode.replaceChild(searchWrapper, this);
document.getElementById("search-wrapper").focus();
But it's not quite working. Should I be setting focus as a callback on replaceChild, or is there some other way to do this?
Try the following:
Live Demo
var searchOrig = document.getElementById("search-wrapper");
var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
searchWrapper.setAttribute('tabindex', '0');
searchOrig.parentElement.replaceChild(searchWrapper, searchOrig);
document.getElementById("search-wrapper").focus();

Replace html in userscript w/o breaking anything?

The below is in my userscript. It doesnt do the alert because when i replace the html i am clobbering it somehow.
How do i replace regular text in a div or span that is literally domain[dot]com so it will appear as domain.com? Well the below works but breaks code running after and other userscripts.
$(function() {
var html = $('body').html();
var res=html.replace(/\[dot\]/g, ".");
$('body').html(res);
//doesnt call, however html is replaced
alert('a');
});
Replace the text in the page instead of replacing in the entire HTML. If you get the entire HTML and put it back, that will make it reparse all the code and put it back as it was when initially loaded, whcih means that any events bound to any elements are gone.
Use a recursive function to find the text nodes in the document and do the replacing on the text in each node:
function replaceText(node, replacer) {
var n = node.childNodes;
for (var i = 0; i < n.length; i++) {
if (n[i].nodeType == 3) {
n[i].nodeValue = replacer(n[i].nodeValue);
} else {
replaceText(n[i], replacer);
}
}
}
$(function(){
replaceText(document.body, function(s){
return s.replace(/\[dot\]/g, '.');
});
});
Demo: http://jsfiddle.net/Guffa/ex83P/
As you see, there is no jQuery in the function, because jQuery only deals with elements, there are no methods to deal with text nodes.
Is this for a specific set of pages or do you plan on doing this across every page you encounter? If specific, try narrowing down your selectors significantly. This way you're not trying to process every span/div on the page (which is obv slow). Firebug should be able to help you.

JavaScript code won't work On My Blogger Site

I have made JavaScript code using the fiddle.com website. But in fiddle I can only make it work by using the
no wrap (body)
option. I'm not sure what this option does. The link for the Fiddle is here. I added this script to my Blogger blog, but it would not work.
Code
function getTotal(){
var form = document.theForm;
var inputs = form.getElementsByTagName('input');
var length = inputs.length;
var total = '0';
for (i = 0; i<length-1; i++){
if(inputs[i].type == 'radio'){
var checked = inputs[i].checked?1:0;
if(checked){
var value = inputs[i].value.split("~~")[0];
total -= -value;
}
}
}
document.getElementById('totalspan').innerHTML="Toplam Fiyat: "+ total + " tl"
total='0';
}
The script is to calculate a total price of the selections. You can see it in the fiddle. Also, I have it on Blogger, but as I said it's not working.
The link to my blog is here.
no wrap (body) means that your script will be inserted in new script tag inside body tag, no wrap (head) means that your script will be inserted in new script tag inside head. You can read about it on jsFiddle help
Other options will wrap your JS code inside particular DOM event handlers (onLoad and onDomReady)
Script errors on your site tells me that calculateTotal is not defined, so please check your naming.
Why do you use string when calculating total? You can safely use native JS parseInt funciton.
Another point that using form click event is wrong, you should use change event of your inputs.
Simplest option for you is to use jQuery like this:
$('[name="CPU"], [name="OperatingSystem"], [name="Case"]').on('change', updateTotal);
function updateTotal {
var total = 0;
// calculate your total here
$('#totalspan').text(total);
}
Please check my 5-min fiddle: http://jsfiddle.net/GDXuS/5/
You could also use data- attributes to store price or any other data (see on jQuery site).
And I'm advice you to study some programming languages.

Categories

Resources