I have a page where a user can click a button which says "Add a Skill" and then it should display an input box where you type in your skill, it should display another input box where your skill level should appear and then a horizontal slider where you select your skill level.
I have table in the database called 'skill_list' which has two columns: id and name. The name field will contain thousands of skills in it which you can select from.
I also need the functionality for it to only post the form if the skill exists in the database.
What I am asking is how to get the autocomplete working with jQuery based on my current code or could someone rewrite it slightly for me?
At the moment I have the following code and it throws up no errors in the firebug console and everything works aas normal but I'm really unsure what I have to do to get this working:
skills.php - auto() function (controller):
public function auto(){
$skill = $_POST['skill-0'];
$query = $this->db->query('SELECT * from skill_list WHERE name LIKE "'.$skill.'%" ORDER by name ASC LIMIT 10');
$data = array();
if ( $query && mysql_num_rows($query) ){
while( $row = mysql_fetch_array($query, MYSQL_ASSOC) ){
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
}
}
echo json_encode($data);
flush();
}
skills.php (view)
<form method="post" action="skills/add" id="container">
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('#autoskill').autocomplete({
source:'skills/auto', minLength:2
});
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>
<button class="addNew submitButton"> Add a Skill </button><br>
<div id="newFields"></div>
<input type="submit" class="submitButton" value="Save Skills">
</form>
Hopefully someone can help, Thanks!
make $name into this
$name = $('<input type="text" class="inputField" id="autoskill-'+$num+'" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
then after
$this.append($name).append($amt).append($slide);
add
$('#autoskill'+$num).autocomplete({
source:'skills/auto', minLength:2
});
and remove the autocomplete line completely from ur ready function
then for json make
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
into
$data[$row['id']]=$row['name']
Related
I am trying to create a simple live search where I can input a city name and it'll return all the relative cities.
This is my code. It works except for one thing. It's only returning a single city on input. Shouldn't it returning multiple cities if the the input word is partially matched with them? Can you tell me what I'm doing wrong?
// HTML
<form action="" method="POST">
<input type="text" id="city-box" class="type-input" name="sel-city" autocomplete="off" value="<?php if(!empty($post_city)) { echo $post_city; }?>" placeholder="Type City Name" />
<input type="hidden" id="city-box-id" name="sel-city-hidden" value="<?php if(!empty($post_city_hidden)) { echo $post_city_hidden; }?>"/>
<div id="display-cities"></div>
<input type="submit" name="search" value="Search" />
</form>
// JAVASCRIPT
<script>
$(document).ready(function() {
$('#display-cities').hide();
$("#city-box").keyup(function() {
var name = $('#city-box').val();
if (name == "") {
$('#display-cities').hide();
} else {
$.ajax({
type: "POST",
url: "snippets/backend-search.php",
dataType: 'json',
cache: false,
data: { term: name },
success: function(data) {
var citydata = '<div class="output-results"><p class="output-p1">' + data.cityname + '</p><p class="output-p2">' + data.provincename + ', '+ data.countryname + '</p></div>';
var citydata2 = '' + data.cityname + ', ' + data.provincename + ', ' + data.countryname + '';
$("#display-cities").html(citydata).show();
$( ".output-results" ).click(function() {
$("#city-box-id").val(data.cityid);
$("#city-box").val(citydata2);
$("#display-cities").html(citydata).hide();
});
}
});
}
});
});
</script>
// BACKEND-SEARCH.PHP
if(isset($_POST["term"])){
$param_term = $_POST["term"] .'%';
$get_city_select = $db->prepare("SELECT cities.city_id, cities.city_name,
provinces.province_id, provinces.province_name, countries.country_id, countries.country_name
FROM cities
LEFT JOIN provinces ON cities.province_id = provinces.province_id
LEFT JOIN countries ON provinces.country_id = countries.country_id
WHERE city_name LIKE :param");
$get_city_select->bindParam(':param', $param_term);
$get_city_select->execute();
$result_city_select = $get_city_select->fetchAll(PDO::FETCH_ASSOC);
if(count($result_city_select) > 0) {
foreach($result_city_select as $row) {
$s_city_id = $row['city_id'];
$s_city_name = $row['city_name'];
$s_province_id = $row['province_id'];
$s_province_name = $row['province_name'];
$s_country_id = $row['country_id'];
$s_country_name = $row['country_name'];
echo json_encode (array("cityid" => "{$s_city_id}", "cityname" => "{$s_city_name}",
"provincename" => "{$s_province_name}", "countryname" => "{$s_country_name}"));
}
}
}
You are calling json_encode each time you output a city result. This will result in multiple bits of JSON. Instead, put all the results in an array and encode that with json_encode.
EDIT:
You have now done:
$arr[] = array (
"cityid" => "{$s_city_id}",
"cityname" => "{$s_city_name}",
"provincename" => "{$s_province_name}",
"countryname" => "{$s_country_name}"
);
Here, you are building a new array for each city result. Instead, do this:
$cities = [];
foreach($result_city_select as $row) {
$city = new \stdClass();
$city->id = $row['city_id'];
// ...more city properties...
array_push($cities, $city);
}
echo json_encode($cities);
For each city, a new anonymous PHP object (stdClass) is created, and its properties are filled with city information. This object instance is then added to the cities array, which is finally sent to stdout as JSON.
Each city will have to be a JSON object, and not an array.
I have the following codes that generate checkboxes from database
< table class="table">
< thead>
< /thead>
< th>
<?php
$oaNamesQuery = "SELECT DISTINCT oaName FROM oaDetails";
$oaNamesQueryExecute = mysqli_query($conn, $oaNamesQuery);
while($oaNamesQueryRow = mysqli_fetch_array($oaNamesQueryExecute)){
$oaName = $oaNamesQueryRow['oaName'];
echo '<div class = "checkbox-group" required style="float:left; margin-right: 25px;"> <input class="checkBoxes" type="checkbox" id="checkBoxArray" name="checkBoxArray[]" value="'.$oaName.'"> '.$oaName.'</div>';
}
?>
< /th>
< /table>
There is another input box as below whereby input type is number
<div class="col-sm">
<label for="numberOfShiftPerDay">Number</label>
<input type="number" class="form-control" id="numberOfShiftPerDay" name="numberOfShiftPerDay" placeholder="No: " onchange="disablingRoutine()" min="1" max="4">
</div>
Example UI as below
When I enter some number, there will be a drop down menu appear according to the number I entered. Eg: If keyed in 1, there will be one drop down list will appear as below using jQuery 'OnChange'. The UI will be as below
What I Need
I need the drop down menu options to be based on user selected checkboxes. Eg: If the user selected checkboxes X, Y and XX, then these drop down list should show X, Y and XX. Can someone help me how to do this?
Edit 1
Added Javascript function on the change routine as suggested by stackoverflow member. But now having duplicate issues. Below the code that I changed
if ($("#numberOfShiftPerDay").val() == 1) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift1').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 2) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift2').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 3) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift3').append('<option>' + cval + '</option>')
});
} else {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift4').append('<option>' + cval + '</option>')
});
}
You can get the selected checkbox values and append to your dropdown list in your onchange function.
Try this:
function disablingRoutine()
{
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
$('#dropdownID').append('<option>'+cval+'</option>')
});
}
Edit 2
function disablingRoutine()
{
cdata = '';
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
cdata += '<option>'+cval+'</option>';
});
$('#dropdownID').html(cdata)
}
I have a problem similar to this resolved question here link!
There are many great answers in this link even extending the OP's problem to multiple radio groups.
(My formatting is the same as in the link but) my problem is that I don't have more than two radio groups, but rather multiple elements in my radio groups using a FOREACH loop.
My PHP is below followed by the script.
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB ");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == NULL) {
echo "";
}
else {
?>
<form method="post">
<input data-group="A" class="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?phpecho"$value<br />\n";}}}?>
</input>
</div>
<div>
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == 0.00) {
echo "";
}
else {
?>
<input data-group="A" class="A" ID="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?php
echo"$value<br />\n";
}}}
?>
</input>
</div>
</form>
Im using the script that came with one of the answers in the link:
<script>
$( document ).ready(function() {
$(function() {
var radios = $('[type=radio]');
$('input:radio').change(function(){
var index = $( this ).index( $('[name=' + this.name + ']') );
var groups = [];
radios.not( $('[name=' + this.name + ']') )
.each(function(v,i) {
$.inArray(this.name, groups) > -1 || groups.push( this.name );
});
$.each(groups, function(i,v) {
$('[name=' + v + ']').eq( index ).prop( 'checked', true );
});
});
});
});
</script>
Try this : You can read the name of selected radio button and find all radio button with same name to select them.
NOTE - $(document).ready(.. and $(function(){.. both are same, so you can use any one of them and not both at same time.
$(function() {
$('input:radio').change(function(){
var name = $(this).prop('name');
$('input:radio[name="'+name+'"]').prop('checked',this.checked);
});
});
EDIT- As OP want to select all radio button with same class name or value, use following code -
For Same Class -
$(function() {
$('input:radio').change(function(){
var className = $(this).prop('class');
$('input:radio[class="'+className +'"]').prop('checked',this.checked);
});
});
For Same Value -
$(function() {
$('input:radio').change(function(){
var radioVal = $(this).val();
$('input:radio[value="'+ radioVal +'"]').prop('checked',this.checked);
});
});
Good day every one. I want to insert my php code in my jquery. I want to show my data in database using PHP and I want to put it in a option box. I used var in jquery plus the code of my php but isn't working. Please help me.
Shows the data:
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
while ($result2 = mysql_fetch_assoc($res)){
$name = $result2["name"];
?>
jquery code(dynamic adding text box)
var nitem =0;
var ntotal = 0;
var option = <?php echo" <option value='$name'>$name</option>";} ?>;
function totalItemExpence(){
ntotal = 0;
$('.expense_cost').each(function(){
if($(this).val() != ""){
ntotal += parseFloat($(this).val());
}
});
//$('#total').val(ntotal);
}
$(document).on('change keyup paste', '.expense_cost', function() {
totalItemExpence();
mytotal();
});
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'<select class="expense_name" id="' + nitem '">"'+ option +'"</select>' +
'<input class="expense_desc" placeholder="Expense Description" id="' + nitem + '" required/>' +
'<input class="expense_cost" onkeypress="return isNumber(event)" placeholder="Expense Cost" id="' + nitem + '" required/> ' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem + " .expense_cost").each(function(){
if($(this).val() != ""){
ntotal -= parseFloat($(this).val());
}
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
Try this for while loop :
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
$options = '';
while ($result2 = mysql_fetch_assoc($res)){
$options .= "<option value='{$result2["name"]}'>{$result2["name"]}</option>";
}
?>
And JS part :
...
var option = "<?php echo $options; ?>";
...
This line:
var option = "<?php echo "<option value='$name'>$name</option>"; ?>";
must be in your .php file, because php code won't be executed in a .js file (that's why it's called .php)...
You can wrap that line in a <style> tag in your .php file
Also, don't forget to add these things --> "
And to remove this one --> }
OK, going to try and explain this properly as I think thats why an answer is escaping me and some users are giving me negative replies as they think I have not tried with research to solve this problem.
I have a page where a user is presented with images within a slide viewer. Each item in the slide viewer is inside a LI element.
When a user chooses a slide, and the form is then submitted, I need the script to update a hidden field so I can take which slide they have chosen into a form. Either by updating onclick or when the form is submitted, it matters not when. The hidden field contains the URL of the image shown at that time.
So, the code I currently have is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="/js/jquery.easing.1.3.js" type="text/javascript"></script>
<!-- this is the slideviewer code -->
<script src="/js/jquery.slideviewer.1.2.js" type="text/javascript"></script>
<!-- this is what I have been trying to update the hidden field -->
<script type="text/javascript">
$(document).ready(function(){
$( "#wl_add" ).submit( function ( event ) { /* form name and id = wl_add */
$('input[name="item_pic_url"]').val($('#mygalthree img').attr('src'));
} );
});
</script>
<!-- the div containing the slide viewer -->
<div id="mygalthree" class="svw"><ul>
<?PHP
foreach($html->find('img') as $e){ // from simple_html_dom
$image = $e->src;
echo '<li><img src="'.$image.'" width=300 alt="" /></li>';
}
// the hidden field to be updated - i am presuming needs to be after the loop which feeds the LI elements
echo '<input type="hidden" name="item_pic_url" value="'.$image.'" />';
?>
</ul></div>
Or, would it be easier to update the hidden field each time a slide is chosen? below you can see the code for the slideviewer - I would have thought I might be able to add
$('input[name="item_pic_url"]').val($('#mygalthree img').attr('src'));
when the user clicks? But I cannot find where to add this either and I have tried nearly every line! Slideviewer code:
jQuery(function(){
jQuery("div.svw").prepend("<img src='/images/spinner.gif' class='ldrgif' alt='loading...'/ >");
});
var j = 0;
var quantofamo = 0;
jQuery.fn.slideView = function(settings) {
settings = jQuery.extend({
easeFunc: "easeInOutExpo",
easeTime: 750,
uiBefore: false,
toolTip: false,
ttOpacity: 0.9
}, settings);
return this.each(function(){
var container = jQuery(this);
container.find("img.ldrgif").remove();
container.removeClass("svw").addClass("stripViewer");
var pictWidth = container.find("img").width();
var pictHeight = container.find("img").height();
var pictEls = container.find("li").size();
var stripViewerWidth = pictWidth*pictEls;
container.find("ul").css("width" , stripViewerWidth);
container.css("width" , pictWidth);
container.css("height" , pictHeight);
container.each(function(i) {
(!settings.uiBefore) ? jQuery(this).after("<div class='stripTransmitter' id='stripTransmitter" + (j) + "'><ul><\/ul><\/div>") : jQuery(this).before("<div class='stripTransmitter' id='stripTransmitter" + (j) + "'><ul><\/ul><\/div>");
jQuery(this).find("li").each(function(n) {
jQuery("div#stripTransmitter" + j + " ul").append("<li><a title='" + jQuery(this).find("img").attr("alt") + "' href='#'>"+(n+1)+"<\/a><\/li>");
});
jQuery("div#stripTransmitter" + j + " a").each(function(z) {
jQuery(this).bind("click", function(){
jQuery(this).addClass("current").parent().parent().find("a").not(jQuery(this)).removeClass("current"); // wow!
var cnt = -(pictWidth*z);
container.find("ul").animate({ left: cnt}, settings.easeTime, settings.easeFunc);
return false;
});
});
container.bind("click", function(e){
var ui = (!settings.uiBefore) ? jQuery(this).next().find("a.current") : jQuery(this).prev().find("a.current");
var bTotal = parseFloat(jQuery(this).css('borderLeftWidth').replace("px", "")) + parseFloat(jQuery(this).css('borderRightWidth').replace("px", ""));
var dOs = jQuery(this).offset();
var zeroLeft = (bTotal/2 + pictWidth) - (e.pageX - dOs.left);
if(zeroLeft >= pictWidth/2) {
var uiprev = ui.parent().prev().find("a");
(jQuery(uiprev).length != 0)? uiprev.trigger("click") : ui.parent().parent().find("a:last").trigger("click");
}
else {
var uinext = ui.parent().next().find("a");
(jQuery(uinext).length != 0)? uinext.trigger("click") : ui.parent().parent().find("a:first").trigger("click");
}
});
jQuery("div#stripTransmitter" + j).css("width" , pictWidth);
jQuery("div#stripTransmitter" + j + " a:first").addClass("current");
jQuery('body').append('<div class="tooltip" style="display:none;"><\/div>');
if(settings.toolTip){
var aref = jQuery("div#stripTransmitter" + j + " a");
aref.live('mousemove', function(e) {
var att = jQuery(this).attr('title');
posX=e.pageX+10;
posY=e.pageY+10;
jQuery('.tooltip').html(att).css({'position': 'absolute', 'top': posY+'px', 'left': posX+'px', 'display': 'block', 'opacity': settings.ttOpacity});
});
aref.live('mouseout', function() {
jQuery('.tooltip').hide();
});
}
});
j++;
});
};
I suggest the same as Josh V.K. but without that ludicrous positioning hack.
<label>
<img src="imagelocation.jpg" />
<input type="radio" name="coolName" value="image_1" style="display: none;" />
</label>
OK, this has been driving me insane, but it is now solved... In the actual slideviewer code, when a user chooses a number of an image, I added a simple onclick to write the value of the hidden field.
jQuery("div#stripTransmitter" + j + " ul").append("<li><a title='" + jQuery(this).find("img").attr("alt") + "' href='#' onClick=\"document.wl_add.item_pic_url.value='" + jQuery(this).find("img").attr("src") + "'\" >"+(n+1)+"<\/a><\/li>");
Thanks for suggestions.
What I would do, rather than updating a hidden field, is assign each image as a label for a radio button. Then when you submit the form it will submit the value of that radio button. You will need to position the radio button left:-9999 or something so that the actual button doesn't show up.
<label>
<img src="imagelocation.jpg" />
<input type="radio" name="coolName" value="image_1" style="margin-left:-99999px;>
</label>
When the click on the image, it will select that radio button and that value will be submitted with the form.