I am writing an ajax live search feature into my software. There are multiple input that need to be ajax searchable on each form. Everything works great except I want the list of results to be displayed in a hovering "p" element right below the input I am currently searching in. Right now I have a "p" with class = "options" right below each input to display the results. When I type, the results are displayed in EVERY "p", that is, hovering under every input. Is there a way to reference just the child of the current input or do I need to use a separate function explicitly referencing the desired for each input? I've tried a lot of child selector options on the internet and none of them have worked. The code is below. Thank you for your advice.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
$('#acctname').val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('div > p').html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('div > p').html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});
Update: this is how my HTML forms are structured.
<form action= "../model/dataentry.php?formname=enter_deposit" method="POST" id="ajaxform" name="ajaxform">
<div class = "label"><p1>Revenue Account Name</p1></div><div class = "field"><input class = "textinput" type="input" name="acctname" id="acctname" value = "" autocomplete="off">
<p class = "options"></p></div>
<div class = "label"><p1>Revenue Account Number</p1></div><div class = "field"><input class = "textinput" type="input" name="acctno" id="acctno" value = "" autocomplete="off">
<p class = "options"></p></div>
<input class = "submit" name = "Submit" type = "button" id = "ajaxsubmit" value = "Submit" >
<input class = "submit" name = "Close" type = "button" id = "close" value = "Close" >
</div>
</form>
Is this what you are looking for?
https://jqueryui.com/autocomplete/
I found a solution to the issue in case anyone is curious. By assigning each div with class "option" an id equal to its parent's id plus "_opt" (i.e. "acctname" input would have a child div with id "acctname_opt"), I can edit div ids dynamically in my functions to place the result list where I want it. Here is my new javascript code. Works flawlessly. Thanks for your help, everyone.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
var clickedid = $(this).attr('id');
var targetid = clickedid.split('_'); //remove the '_opt' suffice to get the target id
$('#' + targetid).val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var optid = id + '_opt'; //set the target element id
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('#' + optid).html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('#' + optid).html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});
Related
I have a form that looks like below.
I have three "white" dropdowns to filter the value for the Equipment Registration Tag dropdown ( The values of the dropdown input field that has the Equipment Registration Tag label will only come out after the user selects values for the three "white" dropdowns). So the Equipment Registration Tag values will differ based on the "white" dropdowns value.
I want it to be a live filter, the dropdown options will change immediately every time user selects the "white" dropdown value. Currently, my approach is to use the onchange=" this.form.submit()" attribute on the "white" dropdowns and return the values after the filter, but I realize this method has a disadvantage which is a user might accidentally submit the form when changing the value of "white" dropdowns. How can I prevent this and only allow users to submit the form by clicking the save button?
$this->Calibration_Location = $request->get('selected_location');
$this->Calibration_Category = $request->get('selected_category');
$this->categories = Equipment::select('Category')->distinct()->get()->toArray();
$this->locations = Equipment::select('Location')->distinct()->get()->toArray();
$matchThese = ['Category' => $this->Calibration_Category, 'Location' => $this->Calibration_Location];
$this->Registration_Select_Tags = Equipment::select('Registration Tag')->distinct()->where($matchThese)->get();
I have also tried jQuery, but I can only trigger by a specified dropdown field, not any one of them.
<script type="text/javascript">
$(document).ready(function() {
var location, category
$('#selected_transfer_location').change(function() {
location = $(this).val();
console.log(location);
$('#selected_transfer_category').change(function() {
category = $(this).val();
console.log(category);
});
// $('#transfer_registration_tag').find('option').not(':first').remove();
$.ajax({
url: 'Transaction/' + location + '/' + category,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response.data != null) {
len = response.data.length;
}
if (len > 0) {
for (var i = 0; i < len; i++) {
var id = response.data[i]['Registration Tag'];
var name = response.data[i]['Registration Tag'];
var option = "<option value='" + id + "'>" + name +
"</option>";
$("#transfer_registration_tag").append(option);
}
}
}
})
});
});
</script>
I hope my question is clear, still new to Laravel and I hope could receive some hints from you.
First approach could be that, you use call ajax Query on change of each on of them and fetch filtered results. Something like this:
$('#dropdown1, #dropdown2, #dropdown3').change(function(){
var val1 = $('#dropdown1').val();
var val2 = $('#dropdown2').val();
var val3 = $('#dropdown3').val();
//And then your ajax call here to fetch filtered results.
});
Only issue is this Ajax call will occur min 3 times, one for each of them.
Second approach could be you give small button below those dropdowns, something like FetchTags. When user selects all the 3 values, will click on that button and you call your ajax onClick of that btn. So that your Ajax will be called only once.
You can use livewire to do that. It easy.
To install it, you have to use composer by taping the fowllowing command:
composer req livewire/livewire
Please check this tutorial to see how to how to do what you want to do using the framework.
I have a textarea that has been dynamically populated,
<textarea class="materialize-textarea validate addCommentTxt"
value="" data-length="250" required name="addCommentTxt"></textarea>
My problem is that whenever I try to get the value of the textarea in ajax, with this code:
$('.btnCommentSubmit').click(function(e){
e.preventDefault();
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/');
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('.addCommentTxt').val(); //GET THE VALUE OF TEXT AREA
$.ajax({
type: 'post',
url: url,
data: {
addCommentTxt:addCommentTxt,
comment_identifier:comment_identifier,
comment_by:comment_by,
},
success: function(){
alert("scs");
showAllComments(comment_identifier);
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
The value that I get is from the first populated textarea, not from the textarea that I sent my data.
For example:
Textarea 1 - I have sent a "first String" comment and it has been inserted successfully.
Textarea 2 - I have sent a "second String" comment, but the inserted data will be "first String" which is from the textarea 1 not in the textarea 2
You need to get the addCommentTxt relative to your btnCommentSubmit so use closest to get your parent form and then use find to get the textarea value
var addCommentTxt = $(this).closest('form').find('.addCommentTxt').val();
Here is my code:
$(".cbtn").click(function(e) {
alert("here");
var id = $(this).attr('id');
var comment = $('input[id$=id]').val();
alert("hay" + id);
alert(comment);
$.post("comments.php", {
id: id,
comment: comment
})
});
});
The id of cbtn and the text field is created dynamically like this:
<input type="text" class="enter_comment value="comments" id="comm<?php echo $row['p_id'];?>"/>
<input type="button" value="enter" class="cbtn" id="<?php echo $row['p_id'];>">
When cbtn is clicked, I want to get the id of text field that ends with the same id as cbtn. But it is returning undefined instead.
You need to concatenate the id variable in the selector, like this:
$(".cbtn").click(function(e) {
var id = this.id;
var comment = $('input[id$=' + id + ']').val();
$.post("comments.php", {
id: id,
comment: comment
})
});
Alternatively, as the id of the text field is the same as the checkbox, but with comm prepended, you could select it by id directly, which would be quicker:
var comment = $('#comm' + id).val();
Or, if the text field is always the element preceding the checkbox, you could negate the need to select by id completely and use the prev() method:
$(".cbtn").click(function(e) {
$.post("comments.php", {
id: this.id,
comment: $(this).prev().val()
})
});
I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.
I have some code to clone the input field directly preceding the clone 'button' renaming the id and name of the field as it goes (shown below): -
$(".clone").live('click', function () {
var doppleganger = $(this).prev(); // Neater referencing.
$(doppleganger).clone().insertAfter(doppleganger);
$(this).prev().attr("id", "input" + increment).attr("name", "input" + increment);
increment++;
return false;
});
.
The form (#adv_magic) data is loaded on the fly with the jquery ajax event and submitted thusly: -
$("#adv_magic").live('submit', function() {
$("#editor_button, #date_select, #search").hide();
$(".loader").show();
$.ajax({
type: "POST",
url: "./scripts/aquire_template.php",
data: $("#adv_magic").serialize(),
success: function(html){
$("#right_container").empty();
$(".loader").fadeOut(350);
$("#right_container").html(html);
}
});
return false;
});
However my cloned input fields are not being processed when the form is posted to my script. I've seen a few tutorials about creating the input fields as an array but i'd rather not mess around with that at this stage if there is anything else I can do.
I'm wondering also if it's to with the way I am serializing the form? I can't post the full code or a link on this occasion unfortunately as the application is not available from the web. Any thoughts on this would be really appreciated! I'm stumped!
Update Sat 10th 20:31 GMT >
I got the following report from the console > post tab in firebug: -
input1 meeting
input2 select date
input3 enter text
input5 NUMBER MISSING
input6 enter text
input7 test
switch 1
Source
input1=meeting&input2=select+date&input3=enter+text&input6=enter+text&input7=test&input5=NUMBER+MISSING&switch=1
Inputs 5/6/7 are cloned elements so presumably they are being passed to the script?
Update Sat 10th 21:06 GMT >
Echoing the string variable before it is being processed by the script shows non of the cloned input fields.
This one worked for me.
<form id="myForm">
<fieldset>
<input type="text" id="input1" name="input1"/><input type="button" value="clone" class="clone"/>
</fieldset>
<input type="submit" value="submit" id="sbmt"/>
</form>
$(".clone").live("click", function(e) {
var count = $("#myForm fieldset").length + 1;
$(this).parent().clone().insertBefore("#sbmt").find("input[type=text]").attr({
"id": "input" + count,
"name": "input" + count
}).val("");
});
$("#myForm").submit(
function(e) {
e = e || window.event;
e.preventDefault();
$.ajax({
type: "GET",
url: "/",
data: $("#myForm").serialize(),
success:function(data){
}
});
return false;
});
demo: http://jsfiddle.net/wFzx5/2/