Issue in select option in Jquery mobile - javascript

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.

Related

JS : .prepend() an option to 2 select doesn't work

I hope the title is self explanatory but i'll try to explain my problem nonetheless.
in my HTML file, i have 2 select, with no option. On the page load, a ajax request is performed to fetch some datas. In the success callback of my Ajax request, i create an option element for every data i just got. I also prepend those newly created option element to both of my select, but the only prepend that works is the one done on the last select
Here are SC of my code, in this examlple, the option have been prepended on the into_APPNAME select only, and not into the from_APPNAME. If i would revert the prepend such as
$("#into_" + repoName).prepend(option)
$("#from_" + repoName).prepend(option)
only from_APPNAME select would have got options in it.
Any ideas what's going on ?
You have to create two different HTML elements or clone the first one you created in order to create a new one. This code for example should populate both of them:
var option1 = $('<option></option>').attr('value', branch).text(branch);
var option2 = $('<option></option>').attr('value', branch).text(branch);
$("#into_" + repoName).prepend(option1);
$("#from_" + repoName).prepend(option2);
Of course better to clone the option1 into the option2
var option2 = $(option1).clone();
Another way can be the following, getting rid of variables:
$("#into_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));
$("#from_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));

Catch all radiobuttons inside a div using jQuery

Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well

Issue with event delegation

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

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

How to generate Divs containing tables with dynamically addable and removable rows? - JSfiddle Added

In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>

Categories

Resources