how to change ids and name of cloned elements? - javascript

i make a select box and i used clone to make dynamic select boxes but my cloned select boxes ids and names are the same how to change ids and name of cloned elements?here is my code:
<script type="text/javascript">
( function($) {
// we can now rely on $ within the safety of our "bodyguard" function
$(document).ready( function() {
$('#add_button').on('click', function() {
var selectClone = $('#event_2').clone(true); // make a copy of select
$('#some_target').append(selectClone); // append to clone select
});
});
}) ( jQuery );
</script>
<?
$strQuery1="SELECT event_id,event_name from events";
$result1 = $GLOBALS ['mysqli']->query ($strQuery1) or die ($GLOBALS ['mysqli']->error . __LINE__);
?>
<select id="event_2" name="event_2">
<? while($ors1 = $result1->fetch_assoc()) {
echo '<option value="'.$ors1['event_id'] .'" >' . $ors1['event_name'] . '</option>';
}
?>
</select>
<button type="button" value="Add" id="add_button">Add Events</button><br />
<div id="some_target">
</div>
i want next cloned element has id and name event_3 and so on how i do this?

This will take care of everything:
$('#secondevent').clone().attr('id', 'newid').attr('name', 'newname').appendTo( "#some_target" );
clone, assign new id, assign new name and apppend to element #some_target.
Fiddle

var selectClone = $('#event_2').clone(true);
selectClone.attr({ id: 'event_3', name: 'event_3'});
$('#some_target').append(selectClone);

This should work just fine:
selectClone.attr('id', 'newValue')
Right after appending it to the new location.

Related

two dependent dropdowns php arrays

I'm trying to substitute the code that uses javascript and arrays which are visible in source code.
I want to be able to create this with php arrays, or use AJAX and have it stored in another file. I don't know how to make the proper php commands or arrays
var cars= new Array();
cars["OTHER"] = new Array("Heavy Machinery","Semi-Truck","Pickup Truck","Sedan","SUV","Misc");
cars["ATV"] = new Array("small","large");
cars["Boat"] = new Array("Under 20 Feet","Over 20 Feet");
cars["Motorcycle"] = new Array("250CC","500CC","700CC","900+");
cars["RV"] = new Array("Under 25 Feet","Over 25 Feet","5th Wheel");
cars["AC"] = new Array("Cobra");
cars["Acura"] = new Array("1.6 EL","1.7 EL","2.3 CL","2.5 TL","3.0 CL","3.2 TL","3.5 RL","CL","CSX","EL","ILX","Integra","Legend","MDX","NSX","NSX-T","RDX","RL","RSX","SLX","TL","TSX","Vigor","ZDX");
cars["Alfa Romeo"] = new Array("145","146","147","155","156","159","164","166","33","75","308","1900","2600","4C","6C","8C","Alfasud","Alfetta","Berlina","Bimotore","Canguro","Corsa","Disco Volante","Duetto","G1","GT","GTV","GTV-6","GTV6","Giulia","Guiletta","GP","Grand Prix","GTA","Iguana","Junior Z","Milano","Montreal","Navajo","P1","P2","P3","Quadrifoglio","RL","RM","Scarabeo","Spider","Sports Car","Sportwagon","Stradle","Tipo","Torpedo");
........................ALL OTHER MAKES AND MODELS ARE IN BETWEEN........................
cars["Yugo"] = new Array("55","Cabrio","GV");
jQuery(document).ready(function($){
$('span.text select').change(function(){
$(this).siblings('.value').text($(this).find('option[value="'+$(this).val()+'"]').text());
});
for ( make in cars )
{
$('#formmake').append('<option value="'+make+'">'+make+'</option>');
}
$('#formmake').change(function(){
var val = $(this).val();
$('#formmodel').html('<option value="">Select Model</option>');
for ( i in cars[val] )
{
$('#formmodel').append('<option value="'+cars[val][i]+'">'+cars[val][i]+'</option>');
}
$('#formmodel').append('<option value="Other">- Other -</option>');
});
$('#formmake, span.text select').each(function(){
var def = $(this).siblings('.value').text();
$(this).find('option[value='+def+']').attr('selected', 'selected');
$(this).change();
});
});
---------------------- this is what i want to do to HIDE the source on the site --------------------
here is my php to get the MAKE but how do I create the model array so that when a user chooses a car the appropriate MODELS will populate in the corresponding dropdown (called Select Model: )
<?php
$car_make = array('ATV','Boat','Motorcycle','Acura','Alfa Romeo','AM General'); //this is only a partial array, it will have all the makes
echo '<select name="car_make">';
for($i = 0; $i < count($car_make);$i++)
{
echo '<option value="'. ($i + 1) . '">' . $car_make[$i] . '</option>';
}
echo '</select>';
?>
how do i create a second array with vehicle models that will use the first array's option value to lookup a make and then pull the corresponding make's from the model array ?
Well you can use jQuery to select the value of the first select menu and then use it to compare with the specific value for make and then display its specific models
var model=new Array();
function getmodel() {
var make=$('select[name=make]').val();
if(make==='toyota'){$("select[name=model]").html('');$("select[name=model]").append("<option value='corolla'>Corolla</option><option value='camry'>Camry</option><option value='hilux'>Hilux</option>");}
if(make==='honda'){$("select[name=model]").html('');$("select[name=model]").append("<option value='civic'>Civic</option><option value='jazz'>Jazz</option><option value='accord'>Accord</option>");}
if(make==='suzuki'){$("select[name=model]").html('');$("select[name=model]").append("<option value='cultus'>Cultus</option><option value='vitara'>Vitara</option>");}
if(make==='bugatti'){$("select[name=model]").html('');$("select[name=model]").append("<option value='veyron'>Veyron</option><option value='chiron'>Chiron</option>");}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SELECT MAKE:
<select name='make' onchange='getmodel();'>
<option value='toyota'>TOYOTA</option>
<option value='honda'>HONDA</option>
<option value='suzuki'>SUZUKI</option>
<option value='bugatti'>BUGATTI</option>
</select>
<br/>
SELECT MODEL
<select name='model'>
</select>

Populate select box from database query based on another select box using only 1 table

Hi guys I am currently creating a website with the main function of booking cars. Therefore the user would be first able to select a car category from the database query which will output the selected car category names. After selecting the car category name, the second select box would then by dynamically updated with a new set of of car names that are associated with the category.
There may have been many similar questions to this however for the website NO jQuery or AJAX can be utilized. And other questions and examples often utilize 2 or more tables however I am using only 1 table for this function.
The example below should show how the Select box should be updated:
Dynamically updated select box.
The table utilized is this:
Table Utilized
My codes are as such:
<?php
session_start();
include "dbconn.php";
$query = "SELECT carid, brand FROM cars";
$result = $dbcnx->query($query);
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
}
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
Car Category:<br />
<select size="1" name="categoriesSelect" id="categoriesSelect">
<option> Select Car Category </option>
<option value="sedan"> Sedan </option>
<option value="mpv"> MPV </option>
<option value="hatch"> Hatchback </option>
</select><br /><br />
Car Brand:<br />
<select id='subcatsSelect'>
</select>
</body>
</html>
I may have identified the error to the php statement:
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
As I can only see the first select box query correctly consisting of the 3 car category of MPV, Sedan and Hatchback.
Currently the all the Car Brand name appears however the results do not correspond with the car category as shown in the database.
Thank You.
As both arrays in PHP follow the same pattern when created the json data will be similar also thus the method to traverse the data should follow that in loadCategories function - so perhaps this:
function updateSubCats(){
var oSelect = document.getElementById("subcatsSelect");
oSelect.options.length = 0;
for( var i in subcats ){
oSelect.options[ i ]=new Option( subcats[ i ].val, subcats[ i ].id );
}
}
Without using Ajax or over complicating things with complex json iteration you could try along these lines. It should be noted that embedding the $_GET variable directly in the sql is not the best option - prepared statements would be better but should give the idea.
<?php
session_start();
include "dbconn.php";
?>
<!docytpe html>
<html>
<head>
<title>Chained select</title>
<script type='text/javascript'>
function bindEvents(){
document.getElementById('categories').addEventListener( 'change', getSubcategories, false );
}
function getSubcategories(e){
var el=e.target ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
location.search='?category='+value;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<form>
<select id='categories'>
<?php
$query = "SELECT carcat FROM cars";
$result = $dbcnx->query($query);
while( $row = $result->fetch_assoc() ){
echo "<option value='{$cat['carcat']}'>{$cat['carcat']}";
}
?>
</select>
<select id='subcategories'>
<?php
if( !empty( $_GET['category'] ) ){
$sql = "SELECT carid, brand FROM cars where carcat='{$_GET['category']}';";
$result = $dbcnx->query( $sql );
if( $result ){
while( $row = $result->fetch_assoc() ){
echo "<option value='{$row['carid']}'>{$row['brand']}";
}
}
}
?>
</select>
</form>
</body>
</html>
Of course it won't, you're accessing your arrays wrong:
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
^^^^^ ^^^^^
Your subcats array is only 2-dimensional, yet you're accessing it as a 3-dimentional array here.

Creating multiple select populated by js array

Ok this is a bit complicated. Basically I populate a select with an array. Then, I want to create another select, and populate it with the same array again. I believe that the populate function is not called properly when a new select is created, but I cannot find when to call it, to populate the created select.
1st: I query my db to get some member names, and use json_encode my resulting array, to create a json array.
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
$json_array = json_encode($result_array);
then I echo that array to a javascript array, and populate a select tag with the result. All this happens on window load.
<script>
var members = <?php echo $json_array; ?>;
function populate()
{
var sel = document.getElementById('members');
var fragment = document.createDocumentFragment();
members.forEach(function(member, index) {
var opt = document.createElement('option');
opt.innerHTML = member;
opt.value = member;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
}
window.onload = populate;
</script>
The html div containing the select:
<div id="Members">
<select id="members"></select>
</div>
<input type="button" value="+" onClick="addInput('Members'); populate();">
and then I use another script to create more divs
<script>
var counter = 1;
var limit = 3;
function addInput(divName)
{
if (counter == limit)
{
var message = document.getElementById("linkLimit");
message.innerHTML = "Maximum amount of links reached";
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select id='members'></select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
However, the resulting selects are never actually populated. I believe that the populate function is not called properly, but I cannot find when to call it, to populate the created select.
Alternatively, for a static amount of select inputs, I tried doing
<div id="Members">
<select id="members" name="members"></select>
<select id="members1" name="members"></select>
<select id="members2" name="members"></select>
</div>
but again, only the first select is populated
By using a for loop and giving members, members1, members2 through an array, all three lists are populated, however, this is not so functional, since I can't know how many members the user will want to select

Create a custom selected list

Well im adding to database some records but i dont like the way i did and wanted to make something way easier for the user and better.
What i did was: http://i.imgur.com/AYrPyCn.jpg
And what i want is: http://i.imgur.com/aKNBTtO.jpg
Well i guess i know how to create the divs geting all the images from database and the horizontal scroll bar but what i dont know is when i select the image that id from image will appear on the input create by me.
Help needed.
Code from what i have:
<select name="id_artigo" id="attribute119">
<?php
do {
?>
<option value="<?php echo $row_artigos['id_artigo']?>" ><?php echo $row_artigos['id_artigo']?></option>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
</select>
<div id="editimg"><p><img src="images/artigos/1.png" id="main" /></p></div>
Js:
$('#attribute119').change(function () {
$('#main').attr('src', 'images/artigos/' + $('#attribute119 :selected').text() + '.png');
});
You can use jQuery slideshow plugin like jcarousel or jssor.
Just do a google search on "jQuery slideshow" or "jQuery carousel".
I recommend you to use jcarousel.
Anas
Since you don't want it to look like a drop-down any more, replace the drop-down with a hidden field, which will hold the ID of the item they select:
<input type="hidden" name="id_artigo" />
(for testing you could use type="text" instead)
Give each of your images a data-id-artigo attribute:
<img class="artigo_img" src="images/artigos/1.png" data-id-artigo="1">
When an image is clicked, update the hidden ID's value:
$('.artigo_img').on('click', function() {
var idArtigo = $(this).data('idArtigo'); // get the artigo ID from the `data-` attribute
$('[name="id_artigo"]').val(idArtigo); // update the value of the hidden field
});
When the form is submitted, id_artigo will be equal to the selected item, just like before.
I see now that you just want to select 1 image, this answer is for selecting multiple images.
(not tested, so there might be some errors)
<style>
.img_holder
{
height:100px;
clear:both;
}
.floating_img
{
float:left;
width:100px;
height:100px;
}
.img_selected
{
border:1px solid black;
}
</style>
<div class="img_holder">
<?php
$img_id_arr = array();
do {
$selected = true; //<--implement if they are selected
$selected_class = '';
if($selected)
$img_id_arr[] = $row_artigos['id_artigo'];
$selected_class = ' img_selected';
}
?>
<div class="floating_img<?php echo $selected_class; ?>" onclick="toggle_img(<?php echo $row_artigos['id_artigo']; ?>);"><img src="images/artigos/<?php echo $row_artigos['id_artigo']; ?>.png" id="main" /></div>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
<input typ="hidden" id="my_selected_images" name="my_selected_images" value="<?php echo implode(';',$img_id_arr); ?>">
<script>
function toggle_img(img_id)
{
var selected_imgs = $('#my_selected_images').value;
var img_arr = selected_imgs.split(";");
var found = false;
var new_arr = [];
for (i = 0; i < img_arr.length; i++) {
if(img_id == img_arr[i])
{
found = true;
//deselect img
}
else{
//leave other item untouched
new_arr.push(img_arr[i]);
}
}
if(!found)
{
new_arr.push(img_id);
//select img
}
$('#my_selected_images').value = new_arr.join(';');
}
</script>
</div>

get multiple checked value in javascript/jquery

I have status id defined in my div tag which is present in a phtml file .Now, I need to fetch its value into the seprate javascript file.
I have use jquery push method for this.
Code in phtml file :
<table class="abc">
<tbody id="checkboxes">
<tr class="r<?php echo $item['id']; ?><?php echo ($item['status_low']?' status-low':''); ?>">
<td><input type="checkbox" name="item" class="row" statusid="<?php echo $item['status_id']; ?>"</td>
<td><?php echo $item['id']; ?></td>
<td><?php echo $item['title']; ?></td>
</tr>
</tbody>
</table>
Code in Javascript File :
var selected = [];
$('#checkboxes input:checked').each(function() {
if ($(this).checked) {
selected.push($(this).attr('statusid'));
}
});
console.log(selected);
When I print selected array, I get a blank output .
Can anyone tell me where am I going wrong ?
Just remove your if condition like bellow. Your selector is just for selected checkboxes, So you don't need that if anyway.
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('statusid'));
});
DEMO
Try this :-
var selected = [];
$("input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
selected.push($(this).attr('statusid'));
}
});
OR
var selected = [];
$("#checkboxes input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
selected.push($(this).attr('statusid'));
}
});
OR
var selected = [];
$("#checkboxes input[type='checkbox']:checked").each(function(){
selected.push($(this).attr('statusid'));
});
Change your JQuery code like this,
$('#checkboxes input:checked')
to
$("#checkboxes input[type='checked']")
your code is:::
var selected = [];
$("#checkboxes input[type='checked']").each(function() {
selected.push($(this).attr('statusid'));
});
console.log(selected);
"#checkboxes input:checked" selector already selecting checked checkboxes so you don't need to check if checkbox is checked or not. See here http://api.jquery.com/checked-selector/
var selected = $.map('#checkboxes input:checked',function(ck,i){
return $(ck).attr('statusid');
})
You could try this one
var selected = $('#checkboxes input:checkbox:checked.row').map(function () {
var cbId = this.id;
return cbId;
}).get();

Categories

Resources