I have the following script which fetches data (branch names) asynchronously via database:
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// return false to prevent default action
return false;
});
}
});
});
});
HTML
<input type="text" class="form-control empty" name="keyword" id="pickup" placeholder=""/>
Everything is working perfectly, When user clicks link the data (branch name) gets added to the text input field, which is exactly what needs to happen, however...
My Problem
After user has clicked on desired link (branch name) I need the remaining links (data / branch names) to get removed...
As can be seen from above image Stellenbosch was selected, thus I need the other links to get removed...
Any advice how I can achieve the following greatly appreciated.
UPDATE
Here is the fetch_branch.php file as requested:
if(mysqli_num_rows($result) < 1 ) // so if we have 0 records acc. to keyword display no records found
{
echo '<div id="item">Ah snap...! No results found :/</div>';
} else {
while ($row = mysqli_fetch_array($result)) //outputs the records
{
$branch = $row['location'];
echo '<a style="cursor:pointer">'.$brach.'</a>';
echo'<br />';
}//while
}//else
}//if
I'm making a different assumption from the other answers here, because I can't understand why you'd want to remove the other links in the dropdown, after clicking one!
As can be seen from above image Stellenbosch was selected, thus I need the other links to get removed...
If that is indeed the case, you'll want to accept #acontell's answer.
However, if you'd like the clicked link to disappear from your list, you might try something like this in the click handler:
$("#results").on("click", "a", function() {
$this = $(this);
$("#pickup").val($this.text());
// Remove the linebreaks output by modal/fetch_branch.php
$this.next('br').remove();
// Remove the clicked <a> tag itself
$this.remove();
// return false to prevent default action
return false;
});
In case you'd like the whole dropdown to disappear when clicked, do this: (which, I think is common, no?)
$("#results").on("click", "a", function() {
$("#pickup").val($(this).text());
$("#results").slideUp();
return false;
});
try $(this).siblings().remove(); inside your click event. so your function should look like this,
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
//------------------
//only this line is newly added
//------------------
$(this).siblings().remove();
//------------------
// return false to prevent default action
return false;
});
}
});
});
});
After selecting the item and setting the text to input add the following code snippet
$(this).siblings().remove();
This removes all the sibling li s of the selected item
or
$( "#results a" ).not(this).remove();
If I'm not mistaken, I think it could be done with a little modification to your code:
...
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// --MODIFICATION-- Remove all elements except this.
$("#results").html(this);
// return false to prevent default action
return false;
});
}
...
The idea is to substitute the html of the link container (it contains all the links) with the HTML of the clicked link. In essence, it will remove all and leave only the clicked one.
Here's a fiddle (without AJAX) that represents the idea. Hope it helps.
Please check this link for a working demo. Click Here
I used dummy data and use changed keyup event to focus for testing you can modify it more (if this helps).
I hope this will help you.
Thanks,
I don't understand you. However, if you mean hide result after link clicked, you can use
$("#results").slideUp('fast');
within onclick event.
Also you can remove other links and live clicked.
$("#results").on("click", "a", function() {
$("#pickup" ).val($(this).text());
$(this).addClass('selected');
$("#results a:not(.selected)").remove();
$(this).removeClass('selected');
return false;
});
Related
As you can see on these photos, I have made an onclick event that checks the value of the first input text field . Even if I change it, it will still give the old value.
Here is my function:
$(document).on('click','#editcustomer-btn-save',function(e) {
var x = $('#id1').val();
console.log(x);
e.preventDefault();
return false;
});
I note your edit screen appears to be in a modal.
Make sure that in your DOM there aren't two IDs with the same name. (One in your main page, and one in the modal)
Are you sure that it doesn't upgrade ?
Try with this
function displayVals() {
var x= $( "id1" ).val();
console.log(x);
}
$( "input" ).change( displayVals );
displayVals();
I've searched for equal questions, but found not a single one for my specific case.
I have an element
<span id="myButton">Click</span>
and a jQuery post-request bound to it
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
console.log( result );
});
});
});
Now, for every time you click the button, it makes a post-request. Makes sense. What I want is a good solution for only executing the post-request, if the result function (.done()) is executed.
For sure, I know to handle that with a variable like var isAjaxRequest = false; setting it to true, and back to false in the resulting function, but maybe there is a better (jQuery build-in) way of doing it.
Here is my solution by now. I would be really great if there are better ones.
var isAjaxRequest = false;
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
if( !isAjaxRequest )
{
isAjaxRequest = true;
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
isAjaxRequest = false;
console.log( result );
});
}
});
});
Thank you =)
I commonly set the button to disabled when it is clicked and then remove the disabled attribute on the callbacks for the POST request.
$(document).on('click', '#button', function () {
$('#button').attr('disabled', true);
$.post('something').done(function () {
$('#button').removeAttr('disabled');
}).fail(function () {
$('#button').removeAttr('disabled');
});
});
This will prevent the button from being clicked again once it has already been clicked.
As per the comments; If you want this behaviour on a span element or others which don't allow the disabled attribute, you could set a class when clicked.
$(document).on('click', 'span#button:not(.disabled)', function () {
$(this).addClass('disabled');
$.post('something').done(function () {
$(this).removeClass('disabled');
}).fail(function () {
$(this).removeClass('disabled');
});
});
The above code will make sure the element can only be clicked if it doesn't have the disabled class. This will also work for the button elements so there is no need to duplicate code for both methods.
I like to use .one() to attach the event handler and re-attach the event after the ajax call is complete. This will handle all cases even when your target doesn't support disabling:
//define handler function
var myButtonHandler = function(e) {
$.post("RESPONDING_WEBPAGE_HERE.php").done(function() {
attachButtonHandler("#mybutton"); //re-attach the click event after AJAX complete
});
}
//attach an event handler that's only good for one click
function attachButtonHandler(selector) {
$(document).one('click', selector, myButtonHandler);
}
//on doc ready, attach the event handler for the first time
$(function() {
attachButtonHandler("#mybutton");
});
So I am attempting to have a modal popup that displays two messages depending on what the user types into the text box. I want the script to check whether the input contains one of two strings, either ME, or TN (as I am looking at doing a postcode checker).
no matter what i try I can't get the popup to display two messages depending on the input. I don't want the form to submit, I just want to grab the contents of what has been typed.
Here's a link to what I have so far (imagine the close icon is in the top right)..
$(document).ready(function () {
var formResult = $('#postcode-form')
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
http://www.muchmorecreative.co.uk/modal_test/basic-modal-testing-jquery-conditions/
try this:
$(document).ready(function() {
var formResult = $('#postcode-form')
var postcodeMe= /^[me]+$/;
$( "#postcode-form" ).click(function(e) {
e.preventDefault();
if ($(this).val().contains(postcodeMe)){
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
The problem is you're setting formResult as a 'global' variable (sorta). It gets its value when the page loads and never changes. You should change your code to get the value when you actually need it, not immediately after page load.
$(document).ready(function () {
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
//move it to here so that you get the value INSIDE the click event
var formResult = $('#postcode-form')
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
A few other minor things to consider:
indexOf returns a number. You should probably do indexOf(postcodeMe) >= 0
You can look at index of HERE
Have tried these two but not happening, played around with it and found a solution..
$(document).ready(function() {
var formResult = $('#postcode-input')
$( "#postcode-button" ).click(function(e) {
e.preventDefault();
if ($('#postcode-input').val().indexOf("ME")!==-1 || $('#postcode- input').val().indexOf("me")!==-1 ){
// perform some task
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
Thanks for the help though!
I would like to get the value of an input and return it to a span. I would like to update the span each time the input is changing. The problem is that i will use it for a colorpicker so the user will not usualy write the color value(maybe paste it). So everytime the input textfield will be updated by the colorpicker js i want to update my own field.
I created a simple code to help you understand what i want to do.
Pressing the + you will change the value of the input field and i would like to get that value and print it in the span. Thank you.
HTML ::
<div>
<input type="text" class="mariinsky" /><button id="inside">+</button>
</div>
<button id="outside">Button</button><br />
input value = <span></span>
JS ::
var i = 0;
jQuery('button#outside').click(function() {
jQuery('div').toggle();
});
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i);
i++;
});
$( '.mariinsky' ).change( function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
http://jsfiddle.net/existence17/9V8ZU/1/
Add .change() to the end of your '+' handler:
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i).change();
i++;
});
That will force the change event to fire and then your code will update the span.
For live DOM changes, use the jQuery on function - the following code would work in your case:
var i = 0;
jQuery('button#outside').click(function() {
jQuery('div').toggle();
});
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i);
i++;
});
$( 'button#inside' ).on('click', function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
jQuery doesn't automatically trigger events through code. You need to do so manually using the .trigger() method.
Adding one line did it for me: jQuery('.mariinsky').trigger("change").
Here's a working example: http://jsfiddle.net/9V8ZU/2/
Also a useful question for reference: How to trigger jQuery change event in code
please use this :
$( '.mariinsky' ).on('keypress keyup keydown click copy cut paste', function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
Fiddle example
all the rest of the provided answers aren't covering the entire options.
My regex & jquery skills are failing me.
I need to hide ALL of the following html where it appears on a page (the following is spat out by a database):
<p><strong>External Links for:</strong></p>
<p></p>
I'd be very grateful for a jsfiddle (or similar) that uses jquery to hide only exactly ALL of the above. (Note: Sometimes there will be data inside the second paragraph. If so, this should remain untouched).
Thanks in advance!
For the record, I have tried to do this myself but my jquery skills are rubbish so best to start with a blank slate as I expect it will only take a few lines of code to implement.
You can iterate over and check if text is External Links for: then hide it or remove it
$(document).ready(function () {
$("p > strong").each(function () {
if ($(this).text() == "External Links for:") {
//$(this).hide();
$(this).closest('p').remove();
}
});
});
DEMO
OR
$(document).ready(function () {
$("p > strong").each(function () {
return $(this).text() === "External Links for:";
}).closest('p').remove();
});
Alternate Way DEMO
Note: Wrap your code in document-ready handler
If you want to return ONLY instances of BOTH paragraphs in a row, you can create a complex filter like so:
$('p').filter(function(i,el) {
var test1 = $(el).html() == "<strong>External Links for:</strong>";
var test2 = $(el).next('p').html() == "";
return test1 && test2;
}).next().addBack().hide(); // or .remove()
http://jsfiddle.net/mblase75/d7fz4/5/
For example like this:
$( function() {
$( 'p>strong' ).each( function() {
$( this ).next( 'p' ).remove();
$( this ).remove();
});
});
demo