Working with Sly's scrolling codes (http://darsa.in/sly/).
Having multiple Sly carousels on a page, I need to fix the ID of the frame
I generate them with '#=basic-XXX', where XXX is the record of the album.
the standard code is this:
var $frame = $('#basic');
var $slidee = $frame.children('ul').eq(0);
var $wrap = $frame.parent();
I try to read the ID, including the attached record number from the database.
var $frame = $("[id^=basic-]"); // start with...
// trying these two lines, but they FAIL
var num = $frame.slice(7);
var $frame = $("#basic-"+num);
//from here $frame should be redefined as #basic-THENUMBER
var $slidee = $frame.children('ul').eq(0);
var $wrap = $frame.parent();
Any idea how I can update var $frame with the ID so it works for the rest of the script?
$("[id^=basic-]") will return the elements that match the selector and you can then use .attr('id') to get the first element's id value. If there is only one element with an id starting with basic- then this will work:
$frame = $("[id^=basic-]").attr('id');
Note that when you use String.slice, character positions start at 0, so I think you probably want:
var num = $frame.slice(6);
See this demo:
var $frame = $("[id^=basic-]").attr('id');
console.log($frame);
var num = $frame.slice(6);
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<span id="basic-355">hello world!</span>
</div>
If you have multiple elements that have matching id's you will need to iterate them using .each or similar:
var $frames = $("[id^=basic-]");
$frames.each(function () {
let id = $(this).attr('id');
console.log(id);
let num = id.slice(6);
console.log(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<span id="basic-355">hello world!</span>
<span id="basic-562">hello world!</span>
</div>
Related
I have a quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.
Can anyone help?
I am wanting to allocate the result that is displayed in a div with id = result to a variable in which I can use to put into a mysql database field upon selection of a dropdown box list which is allocated a price.
This is what I have at moment.
<script>
$("#country").on("change", function(){
var selected = $(this).val();
$("#results").html("Estimated Postage: " + selected);
})
</script>
<div id='result'>Abracadabra</div>
<script>
var a = $('#result').attr('id'); // to extract the id of this div
var b = $('#result').html(); // to extract the html content of this div
var c = $('#result').text(); // to extract only the text from this div
console.log('a = ', a);
console.log('b = ', b);
console.log('c = ', c);
</script>
If the div is dynamically generated after the page loads completely, use a static parent in selector, like this:
$('body #result').html();
I have a javascript function that create Checkbox by drop_down's selection. When I clicked the add button , system will create checkbox(es) with values.
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//var inner_text = tops + '<a href=\'#\' onclick=\'removeElement('+countedName+')\'> [x] </a>';
//var text= document.createTextNode(inner_text);
x.innerHTML=tops;
ni.appendChild(x);
//ni.appendChild(inner_text);
}
I had make some screenshots to explain you my current problems. Please check my screenshot for more clear picture.
This is like this, for an item like ice-cream, customers can add many toppings example , nuts, jelly etc.
Then I have another problem.Created checkbox's are not shown . I can only see square box(es)
Please see my second attached picture below.Seems okay to me.But I can't see any description text(s).
What I am trying to achieve is
to show selection
Calculate the items,they will be generated with checked value. I have already achieve the code to remove the generated toppings. So I want to calculate the total value of generated items and they should be changeable.
Example. if remove a generated item. Total toppings should decrease.Thanks for your help in advance.
For your first problem: In order to display text for a checkbox, you should put checkbox inside label. Here is modified code for you
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//x.innerHTML=tops; We don't need to set text to checkbox.
/* These lines are added */
var label = document.createElement("label");
label.appendChild(x);
var span = document.createElement("span");
span.innerText = tops;
label.appendChild(span);
/* End of added lines */
// Beware that we are adding label to div, instead of checkbox.
ni.appendChild(label);
}
For your second problem: To calculate grand total of cart, you need to define a function (let's say calculateTotal) that implements sort of this pseudocode:
function calculateTotal
begin
get all checkboxes under myDiv
for each selected check box
begin
get check box id
get substring of id, after comma (",")
add substring (price) to total
end
end
This method should be triggered whenever user clicks add item button, remove item button, and checkboxs' onChange events fire.
I guess this answer should address your issue with checkboxes text: https://stackoverflow.com/a/10143276/1492792
i have this code:
This is the addOptions function
<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
var names = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodesname = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodesname[] = $result['code'] . ' - ' . $result['name'];
}
echo json_encode($nominalcodesname);
?>;
function addOptions(select, values)
{
for (var i=0, iLen=values.length; i<iLen; i++)
{
select.appendChild(new Option(names[i],values[i]));
}
}
</script>
then the add row function
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var sagenominalcodeCell = row.insertCell(3);
var elSageNominalCode = document.createElement('select');
elSageNominalCode.type = 'select';
elSageNominalCode.name = 'sagenominalcode' + i;
elSageNominalCode.id = 'sagenominalcode' + i;
sagenominalcodeCell.appendChild(elSageNominalCode);
i++;
}
</script>
and then the HTML
<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>
<input type="button" value="Add" onclick="addRow();" />
it adds the new rows ok but its no populating the select menu with the addOptions function.
is there any way to make it run that function once the new row/select menu has been dynamically created and then the same for all the others created when the addRow function is called?
So, reading your code a little bit more, I see you have
new Option(names[i],values[i])
My question to you is what does new Option return? I don't see code for it anywhere in your question.
Take a look at the spec for appendChild :
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
It needs an element passed in. What you want to do is make a new element using the createElement() function like so:
var option = document.createElement("option");
And then edit the inner html to be what ever you need like this:
option.innerHTML = "your option content here";
Then pass the element in to the append child function:
appendChild(option);
Use jQuery here instead of straight js. My bet is that your listener for click is only bound to the items that are present on the page when it is created. If you set up a listener through jQuery, then it will fire even on components that are dynamically added.
Also from a code structuring stand point, be very careful about writing js with php. Although it sounds fun (like doing drugs in highschool) it is dangerous, frustrating and leads to untestable code (like doing drugs in highschool does).
i have this script i'm using to display random images with hyperlinks. can anyone tell me how i might adapt it to display 5 random images at once, preferably without repeating the same image twice?
Thanks
<script language="JavaScript">
<!--
/*
Random Image Link Script- By JavaScript Kit(http://www.javascriptkit.com)
Over 200+ free JavaScripts here!
Updated: 00/04/25
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="data/adverts/ad1.png"
myimages[2]="data/adverts/ad2.png"
myimages[3]="data/adverts/ad3.png"
myimages[4]="data/adverts/ad4.png"
myimages[5]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[1]="http://www.javascriptkit.com"
imagelinks[2]="http://www.netscape.com"
imagelinks[3]="http://www.microsoft.com"
imagelinks[4]="http://www.dynamicdrive.com"
imagelinks[5]="http://www.freewarejava.com"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
random_imglink()
//-->
</script>
function random_imglink(){
var myimages=new Array();
...
var imagelinks=new Array();
...
var used = [];
var ry;
var howmany = 5;
for (var i = 1; i <= howmany; i++) {
ry=Math.ceil(Math.random()*myimages.length);
while(used.indexOf(ry)!=-1){
ry=Math.ceil(Math.random()*myimages.length);
}
used.push[ry];
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
}
this assumes you're going to put more images in your array than 5.
Instead random and checking with while if you have already chosen an image you can move the choosen image to the end of the array and reduce the variable for the random by one. Example:
function random_imglink(select){
if (select > 5 ) {
// make it fail ...
}
//specify random images below. You can have as many as you wish
var myimages = new Array();
myimages[0]="data/adverts/ad1.png"
myimages[1]="data/adverts/ad2.png"
myimages[2]="data/adverts/ad3.png"
myimages[3]="data/adverts/ad4.png"
myimages[4]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[0]="http://www.javascriptkit.com"
imagelinks[1]="http://www.netscape.com"
imagelinks[2]="http://www.microsoft.com"
imagelinks[3]="http://www.dynamicdrive.com"
imagelinks[4]="http://www.freewarejava.com"
var size = myimages.length
for (var i=0;i<select;i++) {
var index = Math.floor(Math.random() * size);
document.write('<a href='+'"'+imagelinks[index]+'"'+'><img src="'+myimages[index]+'" border=0></a>');
var tmp = myimages[index];
myimages[index] = myimages[size - 1];
myimages[size - 1] = tmp;
tmp = imagelinks[index];
imagelinks[index] = imagelinks[size - 1];
imagelinks[size - 1] = tmp;
--size;
}
}
random_imglink(3);
It could be something like that in one line of code and without creating functions:
<img src="https://www.example.com/images/image-<?php echo rand(1,7); ?>.jpg">
In order to get this to work, you’ll want to name your images: image-1.jpg, image-2.jpg, image-3.jpg....image-7.jpg,
When the page loads, the PHP rand() will echo a random number (in this case, a number between 1 and 7), completing the URL and thus displaying the corresponding image. Source: https://jonbellah.com/load-random-images-with-php/