Okay so i have a combobox with two options.
Now if one of the options is selected a new input field should appear.
echo $this->Form->input('group_id', array( 'id' => 'groupId'));
echo $this->Form->input('clientid',array( 'type' => 'hidden', 'id' => 'id_client',));
And for that i would use Jquery to check the values
<script>
$(document).ready(function () {
$("#groupId").change(function () {
if($(this).val() == 2){
// do set visible
}
})
});
</script>
My question is: how can i change the type of the field to visible? i have tried: $('#groupId').show(); also $('#clientid').get(0).type = 'text';
But didnt seem to work and i am starting to wonder if this is the best way of doing such a thing?
$(this).attr('type', 'text');
You're doing it wrong.
type="hidden" is not appropriate to hide UI elements (form fields or anything else).
You should instead use the CSS attribute display. Change your clientid input type to "text". When groupId is not 2, set display: none on your clientid input. When it's 2, set display: block.
With jQuery, you can use $('#clientid').show() and .hide().
For instance:
<select id="groupId"><!-- options... --></select>
<input type="text" id="clientId" />
<script>
$(document).ready(function () {
function showHideClient() {
var show_client = $(this).val() == 2;
$("#clientId").toggle(show_client); // hide or show
}
// we bind the "change" event to the hide/show checking
$("#groupId").change(showHideClient);
// and we call it at page load to hide the input right away if needed
showHideClient();
});
</script>
Related
Hello I have issue with my jquery code, because when I want to press any key to get query from database that is not working (it is not showing any alert). I think my ajax isn't working very well because I tried to copy other code and didn't work. I want to get data from database with my skills to choose in options
jQuery code
$(document).ready(function () {
$("#skills").click(function () {
alert("test")
});
});
<select class="select2bs4" multiple="multiple" name="ums[]" data-placeholder="Skills"
style="width: 100%;" id="skills">
</select>
And I want to do when I press any key then should show any result in multiple select but at beginning didn't show any alert yet.
I tried to do like "Select2 and Laravel: Ajax Autocomplete" from Laraget website and that wasn't working too
EDIT____
If it's only input with type 'text' it's working fine to show alert
Thank you in advance
Try this
$(document).ready(function () {
$("#skills").change(function () {
alert("test")
});
});
Select will not work with click but with change , but if you want change when you write in select like search bar , replace this :
$("#skills").click(function () {
alert("test")
});
to this if you want to get the change option :
$("#skills").on('change',function () {
alert("test")
});
or this if you want to handle user input :
$("#skills").on('keyup',function () {
alert("test")
});
Background
So I have a table that is populated by a form. Each row can be edited by hitting a edit button. The Edit button opens the form that is populated. I need to auto fill the autocomplete so that the user can see one of His selected course.
How I Cheated
I'm using PHP and Codeigniter server side and am dynamically creating my form based on database. The labels and values are all produced from the Database and populate my JQuery Auto complete (a.k.a datasource variable below). From my controller I'm passing my value to the model and getting the Label from the DB. From there I'm passing it to my view and to my AutoComplete and setting the input value equal to the found label.
I feel dirty having done it this way. The inefficiency of this burns my eyes.
My Goal
I want to use the value that I've gotten and have the autocomplete select it and display it's label client side.
OR
I need to just display the label in the box so the user knows it's not a blank field.
Both options need to allow the user to modify the autocomplete box.
Existing Code
My code for the input looks like this:
<div class="row-start span-2">
<label for="course_code">Course Code </label>
</div>
<div class="row-end span-2">
<input id="course_code">
</div>
My script for the autocomplete looks like this:
<script>
function search_course_code(){
var datasource = [{"value":"1","label":"AAF100 - DL"},{"value":"2","label":"AAF101 - DL+web"},.....];
var searchboxid = "#course_code";
var searchresultid = "#CRSEINVID";
$(searchboxid).autocomplete({
source:datasource,
focus: function( event, ui ) {
$( searchboxid ).val( ui.item.label );
return false;
},
select: function(event,ui){
var UIvalue = ui.item.value;
var UIlabel = ui.item.label;
console.log(UIvalue);
console.log(UIlabel);
$( searchboxid ).val( ui.item.label );
use_search("#search1","#CRSEINVID",UIvalue,UIlabel ); return false;
}
});
};
function use_search(show_select,result_id,uivalue,uilabel){
//loads value to field that takes it's value
$(result_id).val(uivalue);
//Display course below search box
course = "<span>"+uilabel+"</span>";
$(show_select).html(course );
//stops the value from being shown in the search box
return false;
};
$( document ).ready(function() {
search_course_code();
});
</script>
I draw the value from a hidden input with a unique ID simply using JQUERY val() function.
What I've tried
Try 1
Setting value using:
$(searchboxid).val(hiddenInputValue);
Result: Value displayed not the label
Try 2
Using the autocomplete on create method I tried to overwrite the UI object and send it to the select.
ui.item={"value":"","label":""};
ui.item.value=$(hiddenInputValue).val;
this.select(ui);
Result: No observable change, no errors.
Try 3
$(searchboxid).autocomplete("select", hiddenInputValue);
Result:
Uncaught Error: cannot call methods on autocomplete prior to
initialization; attempted to call method 'select'
Try 4
Tried changing value using
$(searchboxid).val(hiddenInputValue);
and having change function detect it and set label with
$( searchboxid ).val( ui.item.label );
Result: Value loaded into input not label
Try 5
Tried Triggering the change function with this:
$("#<?php echo $id;?>").autocomplete("option","change").call(searchBox);
and then setting label. Based on the answer to:
jQuery AutoComplete Trigger Change Event
Result: empty UI object for change function,
Try 6
Tried Triggering the select function with this:
$("#<?php echo $id;?>").autocomplete("option","select",{value:hiddenInputValue}).call(searchBox);
and then using my current select function.
Result: Uncaught Error: undefined is not a function,
Ideas
Ideas 1:
I thought of using the value then searching through the datasource object to find associating label and then using:
$(searchboxid).val(label);
would this work? How would I do it?
Idea 2:
If the value of the input field is set to a value using:
$(searchboxid).val(label);
Would the change function detect it? Not detected used console.log function in change function to give feedback,
So after much research and trying to get this to work I discovered two problems:
that I was using Select2 version 3.5.3 and needed to use text instead of label and :
$myselect.select2("val","somevalue");
The MAJOR source of my problem though was because I was using Web Experience Toolkit tabs and I needed to load the Select 2 after tabs where initialized.
assign the value to the auto complete input element by using
$('#YourAutoCompletBox').val(yourValuefromHiddenControl);
html:
Topic: <input type="text" id="topics" /><input type="hidden" id="topicID" />
<br/><br/><br/><br/>
<p>You selected <span id="results"></span></p>
jQuery:
var topics= [
{
value: "cooking",
label: "Cooking",
id: "1"
},
{
value: "C++",
label: "C++",
id: "2"
},
{
value: "craftsmanship",
label: "Software Craftsmanship",
id: "3"
}
];
$(document).ready(function() {
$( "#topics" ).autocomplete({
minLength: 0,
source: topics,
focus: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
$("#topicID").val(ui.item.id);
$( "#results").text($("#topicID").val());
return false;
}
})
});
Playground : jsfiddle
Many input field and button pairs for ajax request works only for first time. After first request-response other buttons doesn't call ajax function.
There's a data grid list. Each row has a Title field (as input) with a button to call ajax function for updating this field and refresh list.
first time I click on one of the buttons everything works fine, data sends and list refresh with new data. but after this when I click on one of the buttons nothing happens , even function doesn't call.
Where I'm doing mistake?
My ajax function:
$('.titleBtn').click(function(event){
var id = $(this).attr('name');
var title = $('#' + id).attr('value');
var formAction = '".$this->createUrl('article/changeTitle')."';
$.get(formAction,{id:id,title:title},function(result){
$.fn.yiiGridView.update('article-grid');
}
);
event.preventDefault();
});
My grid list:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
'id'=>'Artform',
)); ?>
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'id'=>'article-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'ID',
array(
'header'=>Yii::t('labels','Title'),
'name'=>'Title',
'type'=>'raw',
'value'=> function($data) use ($model) {
return '<input type="text" id="'.$data->ID.'" value="'.$data->Title.'"><button type="button" name="'.$data->ID.'" class="titleBtn" >Update</button>';
},
),
....
),
)); ?>
//Some buttons irrelevant to this subject for submitting whole list.
<?php $this->endWidget('CActiveForm'); ?>
You could set the event using delegate
$('#Artform').delegate('.titleBtn', 'click', function() {
...
});
You need to add afterAjaxUpdate option to your TbGridView and add js code to invoke after ajax update and set your handlers.
When a room_id is selected from the drop down, I use the JS helper to populate the security_deposit and room_rate inputs. The issue is that if I select a room_id, the room_rate_update jQuery change function stops working. However, when page loads and I don't select a room_id, I can type in the room_rate box and it's triggered, but not after I select a room_rate.
The one thing that I think may be causing this is when I select a room_id, the entire div containing the room_rate is updated. It was previously generated by the CakePHP form helper, however, I made sure that the div is replaced by the exact same name, class, id, etc... It's identical to the one that appears when the page loads
Here is the form in my view
echo $this->Form-create('Arrival');
echo $this->Form->input('room_id',array('options' => $room_numbers, 'label'=>'Room Number'));
?>
<div id="room_rate_update">
<?php
echo $this->Form->input('room_rate', array('label' => 'Room Rate (numbers only)'));
?>
</div>
<div id = "security_deposit_update">
<?php
echo $this->Form->input('security_deposit',array('label' => 'Security Deposit (numbers only)'));
?>
</div>
<?php
echo $this->Form->input('balance_upon_arrival',array('label' => 'Balance Due Upon Arrival'));
Here is the JS helper and jQuery function for the updates
//if someone changes the room_rate, this should update the deposit amount
$(document).ready(function(){
$("#ArrivalRoomRate" ).change(function() {
alert('test');
});
});
//populates the room rate when the room is selected
$this->Js->get('#ArrivalRoomId')->event('change',
$this->Js->request(array(
'controller'=>'Arrival',
'action'=>'getRoomRate'
), array(
'update'=>'#room_rate_update',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
))
);
Here is the view for the JS helper POST request
//room_rate_update.ctp
<div class="input text required">
<label for="ArrivalRoomRate">Room Rate </label><input name="data[Arrival][room_rate]" maxlength="10" type="text" id="ArrivalRoomRate" required="required" value="<?php echo $room_rate; ?>">
</div>
So, as I stated. Prior to selecting a room_id, the "test" is triggered. After I select a value
You should have another function, for instance :
function init ()
{
$("#ArrivalRoomRate" ).change(function() {
alert('test');
});
}
After all content refreshed, then call it once. Otherwise, when all content refreshed, this event handler will be invalid for new content, coz it's partial rendering.
You can try with a delegate(aka live) event handler like following:
$(document).ready(function(){
$("body" ).on("change", "#ArrivalRoomRate", function() {
alert('test');
});
});
If you have problem with .on() with jQuery version, then you can use .live() with old jQuery like following:
$("#ArrivalRoomRate").live("click", function() {
alert("test");
});
I am working on a site right now and have discovered that the jquery/javascript that I have implemented for the Search applies the same effect to all search boxes on the page when I click in the input field. By default, it removes the "Search" text and clears it out so that you can type your search term. I only want it to perform this function on the search box that is clicked within, not all search boxes on the page. However, if you look at this example, you'll notice that when you click into the search field at the top of the page, it clears the text out of both. I think I could fix it with .parent() or something, but am a jQuery novice. Any help would be appreciated.
Also don't know quite why the border is showing up around my icon, but I'll fix that.
Here's the search function jQuery:
$(document).ready(function(){
$('.search-box').textdefault({'text':'Search'});
});
(function($){
$.fn.textdefault = function(settings){
var Elements = this;
var settings = $.extend({}, $.fn.textdefault.defaults, settings);
return Elements.each(function(){
if($(Elements).is("input")){ TextDefault( $(Elements) ); }
});
function TextDefault(Input){
if (Input.val().length==0) Input.val(settings.text);
Input.focus(function () {
if (Input.val()==settings.text) Input.val('');
});
Input.blur(function () {
if (Input.val().length==0) Input.val(settings.text);
});
}
};
$.fn.textdefault.defaults = {
text: 'Search'
};
})(jQuery);
Thanks!
Taylor
plugin example
here is the correction.
Elements contains all the elements that are 'passed' to this plugin.
var Elements = this;
By using $(Elements) instead of $(this) in the each function, you
used all inputs as one
return Elements.each(function() {
if ($(this).is("input")) {
TextDefault($(this));
}
});
This line of code should be called to initialize the plugin. So it should be put somewhere outside of the plugin, in a $(document).ready() {} code block for example, since you need the plugin initialized for the inputs on the load of the page.
$('.search-box').textdefault({
'text': 'Search'
});
Use a different selector. Instead of all inputs with a class of "search-box" try giving it a unique ID or class.
$("#search_default").textdefault({'text':'Search'});
or
$(".search-box.defaulttext").textdefault({'text':'Search'});
The HTML would then be
<input type="text" class="search-box defaulttext" ...
or
<input type="text" id="search_default" ...
This is the method that I use, which could also be helpful for you. It won't fire for both objects since it uses $(this) to control just the object being focused/blurred.
$(".search-box").live("focus", function(){
if ( $(this).val() == $(this).attr("rel") ){
$(this).val('');
}
}).live("blur", function(){
if ( $(this).val() == '' ) {
$(this).val( $(this).attr("rel") );
}
}).each( function(){
$(this).attr("rel", $(this).val() );
});
I would try to use a more "jQuery" way to do this. jsFiddle
$('input').focus(function(){
$(this).data('text', $(this).val()).val('');
});
$('input').blur(function(){
if( $(this).val() === "" ) $(this).val( $(this).data('text') );
});