Add audio rows after video rows - javascript

How can I make sure that audio rows gets added after the video rows with the code below. Note that I want it all in the same table. I assume I shouldn't use prepend() the way I do.
The expected result should look like this if you add 3 video rows and 2 audio rows, no matter what order you add them in:
video 3
video 2
video 1
audio 2
audio 1
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
}
else
{
var count = audioCount; audioCount++;
}
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" name="type" value="video" checked="checked" /> Video</label>
<label><input type="radio" name="type" value="audio" /> Audio</label>
<input type="submit" name="submit" value="New Row" />
<table></table>

I am satisfied with the ans by Murali Nepalli but you don't need to go for different if else condition for video and audio when its already there once. I suggest keeping the code optimal. You can verify it on : JSFiddle Verification
So you can simply go for :
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
}
else
{
var count = audioCount; audioCount++;
if( $('tr:contains("audio")').length > 0){
$('<tr><td>' + type + ' ' + count + '</td></tr>').insertBefore($('tr:contains("audio")')[0]);
}else{
$('table').append('<tr><td>' + type + ' ' + count + '</td></tr>');
}
}
});
And it works like a pro.

Try this code, I verified this at https://jsfiddle.net/9cpk51eq/
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
}
else
{
var count = audioCount; audioCount++;
}
if(type=="video"){
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
}else{
if( $('tr:contains("audio")').length > 0){
$('<tr><td>' + type + ' ' + count + '</td></tr>').insertBefore($('tr:contains("audio")')[0]);
}else{
$('table').append('<tr><td>' + type + ' ' + count + '</td></tr>');
}
}
});

Related

JS working in Chrome but not Firefox

This script stopped working in FireFox a couple of weeks ago, around the time I added an SSL certificate to the site. I've confirmed that SSL is being used everywhere, and I've tried disabling all recently installed plugins, to no avail.
I've looked at it with Web Console and don't see any errors there either - though I'm not very experienced with that.
I've also looked at other threads here about js working in Chrome but not FF, but none of the proposed solutions seem to apply to my script.
The problem is that the js is apparently not being called at all - it should show up between the introduction and the "share" graphic.
Any ideas?
This is the page where it should show up, between the text and the "share" graphic: Quiz
And this is the js file: Javascript
Here is the code:
$.each(questions, function (key, value) {
//console.log( key + ": " + value.question ); question = value.question;
qtype = value.qtype;
opts = value.opts;
answer = value.answer;
special = value.special; $('#quiz-form').append('<p> <br>' + parseInt(key + 1) + ") " + question + '</p>'); if (qtype == "radio")
{ opt_array = opts.split(','); for (i = 0; i < opt_array.length; i++)
{ $('#quiz-form').append('<p><input data-ftype="radio" type="radio" name="question_' + key + '" class="question_' + key + '" value="' + opt_array[i] + '"> ' + opt_array[i] + ' </p>'); }
} else if (qtype == "checkbox"}
else if (qtype == "checkbox")
{
opt_array = opts.split(',');
for (i = 0; i<opt_array.length;i++)
{
$('#quiz-form').append('<p><input data-ftype="checkbox" type="checkbox" name="question_' + key + '" class="question_' + key + '" value="'+ opt_array[i] + '"> ' + opt_array[i] + '</p>');
}
}
else if (qtype == "input")
{
$('#quiz-form').append('<p><input data-ftype="text" name="question_' + key + '" type="text" class="question_' + key + '" value="" style = "border:1px solid" ></p>');
} $('#quiz-form').append('<p><input name="answer_' + key + '" type="hidden" value="' + answer + '" class="answer_' + key + '" ></p>');
$('#quiz-form').append('<p class="special" id="special_' + key + '" ><strong>Correct answer(s): ' + answer + '</strong> » Explanation: ' + special + '</p>');
});
$('#quiz-form').append('<p>All done? Check your answers: <input name="submit" id="submit" type="button" value="Submit"></p>'); $('#quiz-form').append('<p>Want another chance? <input name="refresh" id="refresh" type="button" value="Start over"></p>'); $( "#quiz-form" ).on( "click", "#submit", function() {
quest_numb = questions.length;
user_answers = new Array();
real_answers = new Array();
for (i = 0; i <quest_numb;i++)
{
if ($("input[name ='question_" + i + "']").data('ftype')=='radio') { user_answers.push($(":input[type='radio'][name ='question_" + i + "']:checked").val()); } if ($("input[name ='question_" + i + "']").data('ftype')=='text') { user_answers.push($(":input[type='text'][name ='question_" + i + "']").val()); } if ($("input[name ='question_" + i + "']").data('ftype')=='checkbox') {
var chkArray = [];
$(".question_" + i + ":checked").each(function() {
chkArray.push($(this).val());
}); var selected = chkArray.join(',')
user_answers.push(selected); } real_answers.push($(":input[type='hidden'][name ='answer_" + i + "']").val()); // alert($(":input[type='text'][name ='question_"+i+"']").val());
}
points=0;
message='<div id="results">';
inc=1;
for(i=0;i<real_answers.length;i++) {
if (typeof user_answers[i]=='undefined' || user_answers[i]=='')
{ //message+='<p>'+parseInt(i+1) + ')' +' You didn't answer this question.</p>';
$('#special_'+i).text(i+inc+') '+'You didn\'t answer this question.');
$('#special_'+i).show();
$(":input[name ='question_"+i+"']").prop('disabled',true);
}
else if( user_answers[i].toLowerCase().trim()==real_answers[i])
{
points++;
//message+='<p>' +parseInt(i+1) + ')' +' Très bien !</p>';
$('#special_'+i).text(i+inc+') '+'Très bien !');
$('#special_'+i).addClass('correct');
$('#special_'+i).show();
} else
{
$('#special_'+i).text($('#special_'+i).text().replace(i+inc+') '+' ',''));
$('#special_'+i).prepend(i+inc+') '+' ');
$('#special_'+i).show();
}
}
message+='<p> Your score: ' + points + '/' + real_answers.length + '</p>';percent=points*100/real_answers.length;if(percent>=90)
{
message+='<p> Chapeau !</p>';
}
if(percent>=80 && percent<90)
{
message+='<p> Très bien !</p>';
}if(percent>=60 && percent<80)
{
message+='<p> Pas mal.</p>';
}if(percent>=40 && percent<60)
{
message+='<p> Houp ! Il faut étudier un peu plus.</p>';
}
if(percent<40)
{
message+='<p> Oh là là - il faut étudier !</p>';
}message+='</div>';
$('#quiz-form #results').remove();
$('#quiz-form').prepend(message);
$("html, body").animate({ scrollTop: 0 }, "slow");
});
$( "#quiz-form" ).on( "click", "#refresh", function() {
location.reload();
window.scrollTo(0,0);
});
});function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable){return pair[1];}
}
return(false);
}
There are numerous JS errors occurring throughout your code. First and foremost, you need to fix the insecure file references, since you are using SSL, so files like this will not load - either change it to relative paths or replace http with https:
<script src="http://www.feedblitz.com/js/tinybox2/tinybox.js" type="text/javascript">
If you are unsure how to view these errors in your browser, please refer to any of these articles:
https://developer.chrome.com/devtools
https://developer.mozilla.org/en/docs/Tools/Web_Console

Generate arrays using dynamically generated forms

Basically, I'm using JavaScript to dynamically generate a form that allows from multiple entries within a single submission. Here's the code I'm using for that:
function addEvent()
{
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var divIdName = 'my' + num + 'Div';
var newdiv = document.createElement('div');
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<table id="style" style="background-color: #ffffff;"><tr><td colspan="2">Entry ' + num + '<hr \/><\/td><\/tr><tr><td><label>Item 1: <\/td><td><input name="item1_' + num + '" value="" type="text" id="item1" \/><\/label><\/td><\/tr><tr><td><label>Item 2: <\/td><td><input name="item2_' + num + '" type="text" id="item2" \/><\/label><\/td><\/tr><tr><td><label>Item 3: <\/td><td><input type="text" name="item3_' + num + '" id="item3" \/><\/label><\/td><\/tr><tr><td><label>Item 4: <\/td><td><select name="item4_' + num + '" id="item4"><option value="---">---<\/option><option value="opt_1">1<\/option><option value="opt_2">2<\/option><option value="opt_3">3<\/option><option value="opt_4">4<\/option><\/select><\/label><\/td><\/tr><\/table>';
ni.appendChild(newdiv);
}
This works just fine, generating the entries fields I need. Using console in-browser, I've even verified all the names are correct. The issue is that I need to then take the selections and generate output. I've tried several methods, but everything resulted in null values.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i);
item2[i - 1] = document.getElementById('item2_' + i);
item3[i - 1] = document.getElementById('item3_' + i);
item4[i - 1] = document.getElementById('item4_' + i);
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
The output is as follows:
Copy code and paste it into Notepad<br />"Save as" CourseName_Unit_Chapter.html<br /><textarea name="" cols="45" rows="34">header template
["null", "null", "null", "null"]
footer template</textarea>
Now, certain fields can be null, that's fine (I'll do form validation after I get it working), but I'm getting null for every field regardless of what is entered.
I, originally, had the .value on the getElementByIds, but that only results in the script not running when the entries variable is greater than 0 (default), which is why I tried removing them.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i).value;
item2[i - 1] = document.getElementById('item2_' + i).value;
item3[i - 1] = document.getElementById('item3_' + i).value;
item4[i - 1] = document.getElementById('item4_' + i).value;
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
I've also tried variations of multidimensional arrays, instead of four arrays, but got the same results.
The output, as indicated by the removal of the .value on the getElementByIds, is good. Basically, there is something wrong with my attempts to populate the arrays using the dynamically generated forms.
I suspect that the issue with the declaration of the element ID, but I'm not sure how else to declare it. This style of scripting is not my norm. ^^'
Anyone have any ideas on how to fix the for loop to generate the array?
replace all occurences of
itemN[i]
with
itemN[i].value
if that doesnt work add
console.log( itemN[i] )
and see what it outputs

css has to apply only one seat <li> ( restrict multiple select)

bus reservation
The following code generate multilpe <li> and when the user click seats, the selected seats css will change. but i want to restrict the multiple selection. the user has to be allow to select only one seat, if he select second <li> (seat) , then the first one has to go unselect
DEMO : http://demo.techbrij.com/780/seat-reservation-jquery-demo.php
CODE : http://techbrij.com/seat-reservation-with-jquery
$(function () {
var settings = {
rows: 6,
cols: 6,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 30,
seatHeight: 30,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1); // Seat No eg : seatNo = 0+0*0+1 (1)
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString(); // Class each seat class Name=seat row-0 col-0
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li onclick="gettable('+ seatNo+')" class="' + className +" table"+seatNo+ '">'
+'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
First remove the class from all elements, then add it to the selected one.
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$('.' + settings.seatCss).removeClass(settings.selectingSeatCss);
$(this).addClass(settings.selectingSeatCss);
}
});
Change the else part to:
else{
$(this).toggleClass(settings.selectingSeatCss);
$(".settings.selectingSeatCss").not(this).removeClass('settings.selectingSeatCss');
}
try changing the code in click() event with this one.
$('.' + settings.seatCss).click(function () {
$(this).addClass(settings.selectedSeatCss).siblings(this).removeClass(settings.selectedSeatCss);
});
working Demo. Hope it helps you.

how can I modify my jQuery function to update the number counter

I am showing number counter in one of my section. When I add new betslips to the container the numbers are displaying correctly. However, when I delete any of the row the counter is not getting updated. For example if there are 3 rows numbered 1, 2 and 3 and if I delete row number 2 the updated values are 1 and 3. Infact the counter should reset to 1 and 2.
Here is my JS code
Adding the betslip rows
function createSingleBetDiv(betInfo) {
var id = betInfo['betType'] + '_' + betInfo['productId'] + '_' + betInfo['mpid'],
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b>' + singleBetNumber + '. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'] + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to remove betslip
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function decreaseBetSlipCount() {
var length = $("#racingBetSlipCount").text().length,
count = $("#racingBetSlipCount").text().substring(1, length-1),
text;
count = parseInt(count);
if (!isNaN(count)) count--;
if (count == 0) text = noSelections;
else text = count;
$("#racingBetSlipCount").text('(' + text + ')');
}
This could be done using only CSS, e.g:
DEMO jsFiddle
HTML:
<div id="bets">
<div class="bet"> some content</div>
<div class="bet"> some content</div>
<div class="bet"> some content</div>
</div>
CSS:
#bets {
counter-reset: rowNumber;
}
#bets .bet {
counter-increment: rowNumber;
}
#bets .bet::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
All row number will be updated automatically when adding/removing any row.
You can manage to do that with following steps;
Enclose bet no with span,
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '<span>. ' + betInfo['horseName'] + '</b></p>');
and I assume you have aouter div called "your_div"
Call below function after every increase and decrease event
function updateBetNo() {
var counter = 1;
$("#your_div .bet_no").each(function(i, val) {
$(this).text(counter);
counter++;
});
}
Make the betNumber findable:
$(leftDiv).append('<p class="title"><b><span class="singleBetNumber">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
After an insert or delete renumber:
$('.singleBedNumber').each(function(idx, el) {
$(el).html('' + (idx + 1));
});
The first problem I see is that $("#racingBetSlipCount") is likely not selecting what you think it is. Since #racingBetSlipCount is an id selector it will only select one item.
To me you need to wrap the betnumber in something accessible so you can update it without having to parse through the title.
So first you would update the creation of the betTitle:
$(leftDiv).append('<p class="title"><b><span class=\'betNum\'>' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
Then you can loop through each and update the number appropriately.
var count = 1;
$.each($(".betNum"), function(){
$(this).html(count++);
});

Can't find the issue: javascript/jQuery

I have the following function that gets called on the KeyDown event of a link.
Basically I'm trying to move down the table (the application calls it a ListBox). In the first loop what I'm trying to do is see if they use the mouse to click inside the table first and my hope was to find the row value and then manipulate the class (highlight) from there.
Unfortunately right now I'm not even getting that far. When the screen loads and I press the down button, the current row (0) has it's class changed as well as row (1). But on the next down button press the tr_lst says it is undefined. Which then throws the loop off and then I get all sorts of errors.
I tried to implement a jsfiddle, however, I couldn't get it working. But you can see some of the code I'm trying to implement.
function xKeyDown(event,ListBoxVal){
var tr_lst = $('#' + ListBoxVal).find('tr[class="LUGridRowHighlight"]');
var iCount = 0;
for (iCount = 0; iCount <= $('#' + ListBoxVal + ' tr').length; iCount++){
if($('#' + ListBoxVal + ' tr:eq('+iCount+')').attr('id') == tr_lst.attr('id')){
lstRow = iCount;
break;
}
}
if (event.keyCode == 40){
//arrow down
if(parseInt(lstRow) < $('#' + ListBoxVal + ' tr').length)
{
if(parseInt(lstRow) == 0){
document.getElementById(ListBoxVal).focus();
lstRow +=1;
document.getElementById($('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight') .addClass('LUGridRow');
}else{
document.getElementById($('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight') .addClass('LUGridRow');
lstRow +=1;
}
}
...
Update:
After looking into this further... It appears that when I click the down arrow more than once the following code is causing an error:
var tr_lst = $('#' + ListBoxVal).find('tr[class="LUGridRowHighlight"]');
When I try to print this out it is 'undefined'
I'm wondering since I am manipulating the class via jQuery do I need to add a .live somewhere to the find? As I believe when elements are manipulated dynamically the .live comes into play. Any suggestions?
Try this
function xKeyDown(event,ListBoxVal){
var $listBoxVal = $('#' + ListBoxVal);
var trs = $listBoxVal.find('tr');
var tr_lst = $listBoxVal.find('tr.LUGridRowHighlight');
var tr_lst_id = tr_lst.attr('id');
var iCount = 0;
for (iCount = 0; iCount <= trs.length; iCount++){
if($listBoxVal.find('tr:eq('+iCount+')').attr('id') == tr_lst_id){
lstRow = iCount;
break;
}
}
if (event.keyCode == 40){
//arrow down
if(parseInt(lstRow) < $listBoxVal.find('tr').length)
{
if(parseInt(lstRow) == 0){
$listBoxVal.focus();
lstRow +=1;
$("#"+$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$listBoxVal.find(' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight').addClass('LUGridRow');
}else{
$("#"+$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight').addClass('LUGridRow');
lstRow +=1;
}
}
...

Categories