I have the following code:
$("#cc").on('hidden.bs.modal', function (e) {
$("#cc iframe").attr("src", $("#cc iframe").attr("src"));
});
I would like to apply that to 10 different divs in my markup (#cc-1, #cc-2, #cc-3, etc...).
I tried using a for loop so I don't have to rewrite the same code 10 times by doing the following:
for (var i = 1; i < 11; i++) {
$('"#cc-' + i + ' iframe"').on('hidden.bs.modal', function (e) {
$('"#cc-' + i + ' iframe"').attr("src", $('"#cc-' + i + 'iframe"').attr("src"));
});
}
The thing is, I don't know how to concatenate the variable i inside my jQuery selector with everything else.
Please note that I need to target the iframe inside every #cc- div. This is the part what I'm getting trouble with. When adding the iframe after the concatenation of the #cc- with the variable i I get a syntax error.
I hope I made myself clear. Any clues in what I'm doing wrong?
You should be able to concatenate a variable in a selector like you are doing, however you don't need to add quotations.
Change this:
$('"#cc-' + i + ' iframe"')
To this:
$('#cc-' + i + ' iframe')
Also you are forgetting to add a space infront of your iframe class.
Change this:
$('"#cc-' + i + 'iframe"')
To This:
$('#cc-' + i + ' iframe')
Complete Change:
for (var i = 1; i < 11; i++) {
$('#cc-' + i + ' iframe').on('hidden.bs.modal', function (e) {
$('#cc-' + i + ' iframe').attr("src", $('#cc-' + i + ' iframe').attr("src"));
});
}
for (var i = 1; i < 11; i++) {
var mydiv="#cc-"+i;
$("mydiv iframe").on('hidden.bs.modal', function (e) {
$('"#cc-' + i + ' iframe"').attr("src", $('"#cc-' + i + 'iframe"').attr("src"));
});
}
Related
Following previous post the this code works and does the job but I am conscious this is about as DRY as the Pacific on a wet day.
I's be grateful for any suggestions that will make it more efficient.
$( "#cvl_mb_services .content-switch" ).each(function(index, el) {
var parent = $(el).parent().parent().attr("id");
var inputValue = $('#' + parent + ' input[type=radio]:checked').val();
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
$(targetBox).removeClass('cvl-hide');
});
$('#cvl_mb_services .content-switch').on('click', 'input[type="radio"]', function(){
var parent = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var inputValue = $(this).closest('input[type="radio"]').attr("value");
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
if (inputValue == 'content') {
$('#' + parent + ' .cvl-content-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'header') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'footer') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').removeClass('cvl-hide');
}
});
Several points to make it more DRY:
Use only one var keyword, and separate the items with commas. Ex. var asdf = 1, sdfg = '', dfgh = true;
Use multiple selectors so you apply the .addClass action only once. See https://api.jquery.com/multiple-selector/
Find a way to get rid of this duplication, such as perhaps adding/using a class to select the right ancestor: .parent().parent().parent().parent().parent().parent()
Don't duplicate strings like 'cvl-hide' Instead make a variable. Many JavaScript minifiers won't touch strings, so you'll end up with this duplication making your overall file larger than it needs to be.
Make variables for duplicate selectors so jQuery doesn't have to do the same lookup twice. For stuff like $('#cvl_mb_services .content-switch') and even for stuff like $(this) which is duplicated.
This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!
$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});
You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest
Hare is my current function
var listItems = $("#list_li").children();
var count = listItems.length;
var i;
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
If is clicked.
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
}
My code adds up styles to it on click, it works fine, how ever, I need to make it so it would know if its clicked or not, I am using loop, because its news feed and it can get more and more, so without the struggle automatically know what to align.
I need something like this
var autoIncresingVar.i = 0;
so when it comes to the 1st one on loop, it would set it to 1 and on click check with "if" its clicked or not.
Let me try to explain Note that I know its not real code
each(i > 5) {
var newEl_"i" = 0;
on first element click
if {newEL_1 == 0) {
addClasses
newEL_i = 1;
} else if)newEl_1 == 1) {
removeClasses
newEL_i = 0;
}
}
You can use .hasClass() function for check if the current node has the 'active' class. If yes, remove it. Else, add it.
Example :
$("#news_" + the_i + " h2").click(function () {
if (!$('#news_' + the_i).hasClass('active'))
{
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
}
else
{
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
One approach would be to use .data() to set a property at an object where value is toggled between 0 and 1 at each click event
$("#news_" + the_i + " h2").data("clicked", 0)
.on("click", function() {
if (!$(this).data().clicked) {
// do stuff with `$(this).data().clicked` : `0`
} else {
// do stuff with `$(this).data().clicked` : `1`
}
// set `$(this).data().clicked` to `1` or `0`
$(this).data().clicked = !$(this).data().clicked ? 1 : 0;
})
Use below code.
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').toggleClass('active');
$('#news_' + the_i + ' h2').toggleClass('active');
$('#news_' + the_i + ' img').toggleClass('active');
$('#news_' + the_i).toggleClass('active');
}
});
}
you can use the add attribute function to add an on click event to each element
http://coursesweb.net/jquery/add-change-remove-attribute-jquery
I seem to be unable to check if a audio file exists before it actions anything due to No Access-Control-Allow-Origin'.
Is it possible to have this and if so, how ?
pText[n] = any word, for example: and, about.
But googles API do not hold names, so I need to check if a name is added to the text, and if so, use a different source url.
// audio check
var audioCheck = $.get('https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3');
console.log(audioCheck);
I have also tried $.ajax but without success.
This is the full script so you can see what I am doing
function populate(pText) {
for(var n=0; n < pText.length; n++) {
// audio check
var audioCheck = $.get('https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3');
console.log(audioCheck);
// if(audioCheck) { link is live } else { link is 404 }
//console.log(pText[n]);
$('[name=p1_1]').append('<span id="s' + n + '"><audio id="a' + n + '" src="https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3" type="audio/mpeg"></audio>' + pText[n] + '</span> ');
}
}
And help would be appreciated :)
I have managed to resolve this using the simple method of onerror
Here is the full code :)
function populate(pText) {
var tex = '';
for(var n=0; n < pText.length; n++) {
//console.log(pText[n]);
tex += '<span id="s' + n + '"><audio id="a' + n + '" src="https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3" onerror="mediaerro(' + n + ',"' + pText[n] +'")" type=audio/mpeg"></audio>' + pText[n] + ' </span>';
}
$('[name=p1Text]').html(tex);
}
$(document).on("click", "span", function() {
$(this).find('audio')[0].play();
});
mediaerro = function(id, word) {
console.log(word);
switch(word) {
case "Rocko":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/rocko.mp3');
break;
case "Caroline":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/caroline.mp3');
break;
case "Benji":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/benji.mp3');
break;
}
};
Using the dynamic audio id and managed to create a function based on an error, which replaces the broken link with a new one where the new recording is. Works a treat!
Firstly, I was trying to replace some contents in a div container using html() in Javascript on click. The problem using this approach is it only put the last value in the array.
So, I used append() instead. But it doesn't work like what I have expected. Well, it does append text in the for loops, but after a click, it just appends the content without removing the previous content like what html() does.
Here is how I implement it:
<div id="events-content"></div>
// using Responsive Calendar js
onMonthChange: function(events) {
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},
...
How do I replace the previous appended text using Javascript?
I'm using this in Responsive Calendar JS
well, you could do something like this...
Prepare all the markup in the loop.
var html = "";
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
html += '<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>';
}
$('#events-content').html(html);
Clear the html before the for loop/append mechanism.
Use .empty()
onMonthChange: function(events) {
$('#events-content').empty() //or $('#events-content').html('');
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},