jQuery

16K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

Share tech news, updates, or what's on your mind.

Sign up to Post

See my JQuery code below. Can you please advise the best way to reduce the amount of duplicate code. You will notice variables are duplicated, but when I move them out of the event functions the process no longer works. I have also adding them in a $.getScript(); function, but this causes a problem too. Any advice appreciated.

function loadtooltip() {
	$('[data-toggle="tooltip"]').tooltip();
}

function getmediafilter(elem) {
	
		if (elem.length > 0) {
			return elem.data("media-filter-value");
		}
	
}

$(document).ready(function() {
		
		$('#ListResults').html('<div class="FirstLoad"><img src="/materials/guide2/images/ajax-loader.gif" width="31" height="31" alt="Loading..."/></div>');
	
		var hash = window.location.hash;
	
		if (hash.substring(0, 6).toLowerCase() == "#page=" && hash.length > 6) {

			var page_hash_num = hash.substring(6);
	
		}
				
	    $.ajax({
          url: 'media_script.php',
		  data: { 
			  page: page_hash_num
		  },
          dataType: 'html',
          type: 'POST',
		  success: function(data) {   
				
        		$( "#ListResults" ).html( data );
			  	
			  	loadtooltip();
				$.getScript("js/media_filter_sorts.js");
				$('.selectpicker').selectpicker();
																	
    		}
			
		 });
	
	
		// Start of page number change
		$('#ListResults').on('click','.pagination a', function(event) {
				event.preventDefault();
			
				var page_num = $(this).attr('rel');
				var items_per_page = $( "#ListResults #items-per-page" ).val();
			
				

Open in new window

0
Learn by Doing. Anytime. Anywhere.
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

Greetings again,

I have this RadioButtonList control with a Yes or option in Repeater control.

                 Purchased:<asp:radiobuttonlist ID="rblType" runat="server" RepeatDirection="Horizontal" TextAlign="Right" style="display:inline;">
                 <asp:ListItem Text="New" />
                 <asp:ListItem Text="Used" />
                </asp:RadioButtonList>

Open in new window


All I am trying to do is to ensure that user chooses either Yes or No before continuing.

I have done a lot RadioButtonList validations but have not found anything that works with Repeater control.

Any ideas experts?
0
Hi all,
I have a small bit of jquery code that when clicked adds a text field, how can I have the field thats been added removed when a user clicks on the X?

You can see what I have so far at:

http://www.dnx.org/tope/1.html
0
I have a few dynamically created checkbox lists. I am using the below code to move the selected checkboxes to the top of the list.

function movefilters(elem) {
	/* Start of move checked items to the top */
	$(".media-search-list input:checkbox:checked").parent().each(function(){
		$(this).prependTo($(this).parent());
		$(this).animate({ scrollTop: 0 }, "fast");
	});
	/* End of move checked items to the top */
}

Open in new window


I would also like to sort the selected checkboxes alphabetically. Can you please advise how I would adapt the above code to do this?

Below is some of my html code for reference.

<ul class="media-search-list">
  <li data-search-term="architectural design">
    <input data-media-filter-value="Architectural design" id="architectural_design" type="checkbox">
    <label for="architectural_design"> <span class="label-title">Architectural design</span> <span class="label-title-quality">(25)</span> </label>
  </li>
  <li data-search-term="backlits">
    <input data-media-filter-value="Backlits" id="backlits" type="checkbox">
    <label for="backlits"> <span class="label-title">Backlits</span> <span class="label-title-quality">(15)</span> </label>
  </li>
  <li data-search-term="wall decor">
    <input data-media-filter-value="Wall decor" id="wall_decor" type="checkbox">
    <label for="wall_decor"> <span class="label-title">Wall decor</span> <span class="label-title-quality">(23)</span> </label>
  </li>
</ul>

Open in new window

0
On this page:
http://groupplanner.gallitin.com/flight/create?depart=07%2F20%2F2017&return=08%2F05%2F2017&tripID=22&tripName=ABC#

I have the button "Add Flight" and it clones the input you see there, the issue is that the name of the fields are:

com0[]airline[]
com0[]flightNumber[]
com0[]departing[]
com0[]seatNumber[]

Open in new window


When cloning I need the com0 to increase to com1, if cloned again then com2 etc...
0
I am using ajax to output filtered list results on a page. Is it possible to go back to the previous filtered results? Please note I am not wanting to go back to the previous url using history.back()

What would be the best way to do this? Would I need to use URL parameters?
0
See my original code which worked correctly as required...

$(document).ready(function() {
	
		// Start of checkbox change
		$('#ListResults').on('change','input[type="checkbox"]', function() {
			
				$('.loadingDiv').show();
				var page_num = $('.pagination .active a').attr('rel');
				
				if ($(".media-filter-brand input:checkbox:checked").length > 0) {
						var media_filter_brand_value = $(".media-filter-brand input:checkbox:checked").data("media-filter-value");
				}
			
				$.ajax({
				  url: 'media_script.php',
				  data: { 
					  page: page_num,
					  brand: media_filter_brand_value
					  filterchange: "true"
				  },
				  dataType: 'html',
				  type: 'POST',
				  success: function(data) {   

						$( "#ListResults" ).html( data );
					  	$('.loadingDiv').hide();
					  	
					  	
					  
					}

				 });
			
		});
		// End of checkbox change

});

Open in new window


You will notice an if statement. I want to reuse this if statement elsewhere so instead of duplicating code I tried putting it in a function like below...

function getmediafilter() {
	
				if ($(".media-filter-brand input:checkbox:checked").length > 0) {
						var media_filter_brand_value = $(".media-filter-brand input:checkbox:checked").data("media-filter-value");
				}
	
}

$(document).ready(function() {
	
		// Start of checkbox change
		$('#ListResults').on('change','input[type="checkbox"]', function() {
			
				$('.loadingDiv').show();
				var page_num = $('.pagination .active a').attr('rel');
				
				getmediafilter();
			
				$.ajax({
				  url: 'media_script.php',
				  data: { 
					  page: page_num,
					  brand: media_filter_brand_value
					  filterchange: "true"
				  },
				  dataType: 'html',
				  type: 'POST',
				  success: function(data) {   

						$( "#ListResults" ).html( data );
					  	$('.loadingDiv').hide();
					  	
					  	
					  
					}

				 });
			
		});
		// End of checkbox change

});

Open in new window


However in doing this the code no longer works. I am no longer getting a result for the variable "media_filter_brand_value". What am I doing wrong?
0
I have a REST call using jQuery Ajax and it works fine on every browser except for IE11.  When I make this POST call,  I get back a 400 error and the data doesn't get written.

Any advise on this would be greatly appreciated.
0
I have the cloning, piece working fine, but just realized when I click "Add Flight" to clone and try to select the Departure Time only my original picker is working.  How can I fix this?

http://groupplanner.gallitin.com/flight/create?tripID=21&tripName=Iowa&depart=07%2F20%2F2017&return=07%2F27%2F2017
0
I have recently started learning about the FuelPHP framework and I have a question that I thought I would post here first, instead of the FuelPHP Forum.

I have been working on understanding how to use the framework as intended by the creators, and I think I'm doing a fair job of that, except possibly with regards to using external jQuery libraries.

I have a simple CRUD application that I built  as a proof of concept for using a third party jQuery DateTimePicker library.

This is the jQuery DateTimePicker library that I found and used.



FuelPHP DateTimePicker Sample - dtpsample
This is not including the public asset folder that contains the actual Javascript and CSS.

Model

fuel/app/classes/model/dtpsample.php

This includes data validation.  Each field is important.  It is important to not rely only on the Javascript front end.  I could improve the validation, but this is a start.

<?php
class Model_Dtpsample extends Model_Crud
{
	protected static $_table_name = 'dtpsample';
	
	public static function validate($factory)
	{
		$val = Validation::forge($factory);
		$val->add_field('name', 'Name', 'required|max_length[255]');
		$val->add_field('event_date', 'Event Date', 'required');
		

		return $val;
	}

}

Open in new window


View Template

fuel/app/views/template_dtpsample.php

I want to specifically point out this piece of code regarding my question. The main question I have is have it properly separated concerns?  I want to have the application display the Date and Time selected in the input box directly above the calendar/time select control as indicated by this screenshot.

dtpsample create new entry
Notice that I have used  Asset::css and Asset::js to load the require asset files.


Open in new window

0
How to Create Failover DNS Record Sets in Route 53
How to Create Failover DNS Record Sets in Route 53

Route 53 has the ability to easily configure DNS record sets specifically for failover scenarios. These failover record sets can be configured to failover to full-blown deployments in other regions or to a static HTML page that informs your customers of the issue.

Here's my code:

<script>
									
					$('#header_text').html('Click on the "Yes" button if the name listed below is you.<br>Otherwise, click "No."');		
					
					$('#verifyUseryes').on('mouseover click', function(event){
						if(event.type==="mouseover")
						{
							$('#header_text').html('After you click "Yes," please give the next page a moment to load.');
						}
						else if(event.type==="mouseleave")
						{
							$('#header_text').html('Click on the "Yes" button if the name listed below is you.<br>Otherwise, click "No."');
						}
						else if(event.type==="click")
						{
							window.location='$portalLink';
						}
					});
					$('#verifyUserno').click(function(){
						$('#header_text').html('Please enter your personal information and click on "submit!"');		
						$('.step_1').show();
						$('#window').html('');
					});
					</script>

Open in new window


Everything is working just like I want it to save one thing...

When the user mouse's away from the "ye" button, I want the text in my "#header_text" div to go back to "Click on the "Yes" button if the name listed below is you.<br>Otherwise, click "No."".

Right now, it doesn't and I don't know why.

How can I make the text in my #header_text div revert to "Click on the "yes" button when the user mouse's away from the button?

Thanks!
0
I'm trying to apply a minor customization to a WordPress admin screen, and would like to figure out how to populate the closest text input field with radio button value on click using Javascript / jQuery.  

The HTML that I currently have in place is as follows:

 <div class="rwmb-input">

  <input size="30" type="text" class="rwmb-text" id="fave_plan_title" name="floor_plans[0][fave_plan_title]">

  <div class="floor-plan-titles">

      <input class="plan-title" type="radio" name="plan-title" id="plan-title1" value="First Floor">First Floor 
      <input class="plan-title" type="radio" name="plan-title" id="plan-title2" value="Second Floor">Second Floor
      <input class="plan-title" type="radio" name="plan-title" id="plan-title3" value="">Custom

  </div>

</div>

Open in new window


To clarify .. I'd like to have it so that when you click on one of the 3 different radio buttons, I'd like for the text input field that's above them to be populated with that radio button's value (ie: either "First Floor", "Second Floor", or "" .... nothing / clear the field).

I'd normally do this by using the text input field's unique ID attribute selector .. but these text input fields are being generated dynamically, so I'd prefer to just traverse the DOM somehow and to just populate the text input field that's above the radio buttons.

Also .. note that I need to implement this using jQuery's noconflict mode (which uses "jQuery" prefixes instead of "$").

Would someone here be so kind as to provide me with a Javascript function that would allow me to accomplish this?

Thanks!
- Yvan
0
I want to check for the presence of a substring within a string using a PHP variable. Something like this:

<?php 

$something="A string that contains the word script";

?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery Text Exchange</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>

<script>

var testStr = <?php echo $something;?>

if ($(testStr:contains("check")).length > 0)
{
	 alert("String Found");
}
	

</script>
</body>
</html>

Open in new window


So, tell me if the word "check" shows up in the PHP variable $something. How can I do this?
0
So I've got a function in PHP. If no records are found as a result of a SELECT statement, then right now, the syntax I'm working on has this:

echo "We were unable to match the info you provided.";

I want to instead, load some text via JQuery into a div. Right now, I've got this:

echo "<script>$('#header_text').html('We were unable to match the information you provided.\n Please try again.');</script>";

It's not working. I think I know why in that what I've got currently is something that's put in motion by an action of some kind. A click, a button - something. Without that "event," I don't have anything.

Let me know if that's accurate and, if you would, also tell me how I can use JQuery to load some new text into the <div> rather than simply echoing a message.

Thanks!
0
On this page: http://groupplanner.gallitin.com/flight/create?tripID=16&tripName=Cancun

I have a button to add flight and when clicked it clones the form as expected.  When I click any of the remove buttons it removes the entire form though.  How can I fix this?
0
Here's what the programmer prior to me has in place:

$out .= <<<OUT
                              <script>
                              var text=$('#header_text').text();
                              $('#header_text').text('Click on the "Yes" button if the name listed below is you. Otherwise, click "No."');            
                              
                              $('#verifyUseryes').click(function(){
                                    window.location='$portalLink';
                              });
                              $('#verifyUserno').click(function(){
                                    $('#header_text').text('Please enter your personal information and click on "submit!"');            
                                    $('#step_1').show();
                                    $('#window').html('');
                              });
                              </script>
OUT;

They used HEREDOC, which is fine, but the challenge I'm running into is that when I try to do this:

$('#header_text').text('Click on the "Yes" button if the name listed below is you.\nOtherwise, click "No."');

or this...

$('#header_text').text('Click on the "Yes" button if the name listed below is you. <br>Otherwise, click "No."');

I get the actual characters ("\n" or "<br>") rather than the actual line break.

I want to maintain the HEREDOC dynamic, at least for now. Any suggestions on how to get that line break happening?
0
Using the documentation found here http://vinceg.github.io/twitter-bootstrap-wizard/ I have created a tabbed form wizard with Parsley validation.
JSFiddle here
I have the form validating perfectly when using the top tabs to move between tab-panes however I am having trouble with the "next" and "previous" buttons.
On initial click of the "Next" button on the first tab-pane the validation seems to work fine however this is where the trouble begins. The "next" button then renders itself "disabled" and does not work any more.
From what I can read the trouble begins on line 2 of my js. Line 3 (commented out) is my attempt at a fix but witht success.
Experts required.
N
0
Hi all, I am still a jquery beginner.
I used the following code to make all checkbox 'selected'. I could see it happened.
But when I ran the program, I'd got the following problems:

(1) it showed '0' was actually selected.
     I need to see the 'checked' checkbox are really selected.
(2) In the current situation, if I 'unchecked' one of checkboxes (suppose the selectall checkbox is now checked), the 'selectall' checkbox is still 'checked'. It should suppose to be 'unchecked'. And definitely still counted '0' was selected.

Would you please help to correct the following code to what I expected result?

$('#selectAll').change(function(){
   var table =  $("#myTable").DataTable();
   var cells = table.cells( ).nodes();
   $( cells ).find(':checkbox').prop('checked', $(this).is(':checked'));         
});

check the selected table length:
alert('table length:'+table.rows('.selected').data().length);

Many thanks,
Sam.
0
I have a smart table with 2 columns. I want to have a mouseover with a popup for the second column to display more information. I found this link I'm following this example  http://plnkr.co/edit/3KiZdZsxwy6GDLoy6DhV?p=preview

I've spent at least 4 hours on this and still can't find a solution. I think it might be my injection of ui-bootstrap per this link
Possible explanation

You can see what I'm doing here:

1.  http://147.75.0.124:88   Log in with admin@admin.test and Password321$

2. Click on "Immigration" and click on the link under it

3. Look at Chrome's console and you see the error.

The error and what I've done

1. I get this error Unknown provider: $uibModalProvider <- $uibModal <- chapterCntrl

2. I made sure I have bootstrap.js and bootstrap-tpls.js
3. In module.js, I have this and I have a reference to it in the page  
angular.module('lawApp',   ['ui.bootstrap']);

Open in new window

4. I checked the bootstrap version.
5. In "chapterCntrl", I tried $uibModalInstance, $uibInstance and $uibModal.  I think $uibModal is correct but I still get the error
6. I changed "chapterCntrl" to below but I get an error with mainCntrl not being defined if  do below

(function () {
    'use strict';
    angular.module('lawApp','ui.bootstrap')

        .controller('chapterCntrl', chapterController);

Open in new window


What am I missing? I still think it's how I inject ui.bootstrap but don't know what else to try.
0
What does it mean to be "Always On"?
LVL 4
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

I have a textbox that use for my calendar

$("#txtDueBackDate").datepicker({
            formatDate: data.formatDueBackDate,
        });

Open in new window


When user initiates the page the textbox filled up with a date like 7\12\2017.
Now when I click on the calendar I would like to highlight two dates
1. the date of today.
2. the date which show at the textbox.

Please, Help.

Thanks,
0
I have a custom post type called manu-color for Manufacturer Colors. Each manufacturer color, there are four custom fields called primary color, secondary color, third color and fourth color.

So basically if manufacturer color is British Racing Green then primary color will be olive green, secondary color will be red, third color will be silver and fourth will be black

I am displaying all the manufacturer colors in a select box, but where I am stuck is when a color is selected I have want to show the primary, secondary, third and fourth colors of the selected manufacturer color in a radio button and make them checked

Here is my code for my select box

<?php
$args = array( 
    'post_type' => 'manu-color', 
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',

);

$manu_colors = get_posts( $args );   
echo '<div id="manu-colors-content"><select id="manu-colors">';
 echo '<option class="default" value="-1">select manufacturer color</option>';
 foreach ( $manu_colors as $post ) {
     $manu_color_slug = $post->post_name;
     echo '<option class="'. $manu_color_slug .'">'. get_the_title() . '</option>';
 }
echo '</select></div>';
?>

Open in new window


here are my four radio button

<label for="primary_color"><input id="primary_color type="radio" name="primary_color" value="need to pass primary color here"><span>primary color name</span></label>
<label for="secondary_color"><input id="secondary_color type="radio" name="secondary_color" value="need to pass secondary color here"><span>secondary color name</span></label>
<label for="third_color"><input id="third_color type="radio" name="third_color" value="need to pass third color here"><span>third color name</span></label>
<label for="fourth_color"><input id="fourth_color type="radio" name="fourth_color" value="need to pass fourth color here"><span>fourth color name</span></label>

Open in new window


I am open to any advice as I have to display those 4 colors other wise customer won't know what a manufacturer color is

Thanks
0
This is the modal
<div id="mdlEdit" class="modal fade" data-backdrop="false" style="background-color: rgba(0, 0, 0, 0.5);">
            <div class="modal-dialog">
                <div class="modal-content">
                     <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="hdrEdit" runat="server"></h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="iID" class="control-label col-xs-5"><span class= >*&nbsp;</span>ID</label>
                            <div>
                                <input type="number" class="form-control" id="iID" placeholder="Enter ID" runat="server" maxlength="30" name="iID" /> 
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="iTableID" class="control-label col-xs-5"><span class="required">*&nbsp;</span>Table ID</label>
                            <div>
                                <input type="number" class="form-control" id="iTableID" placeholder="Enter Table ID" runat="server" maxlength="10" name="iTableID" /> 
                            </div>
                        </div>
                         <div class="form-group">
                            <label for="iFieldName"

Open in new window

0
Hello
I have a script that works perfectly using localhost, but when I upload to server, it doesn't fire at all. There are no errors in firebug and all libraries and files are in place. It dosen't even fire a simple alert that I tried in this script.

I would be grateful if someone could shed some light as to how I can troubleshoot this. Many thanks.

PHP: V5.4.45
OS: OS: CentOS 6.5 (Final)
Plesk version: 12.0.18 Update #99


<script type="text/javascript">
	
  var counter = 0;
  //console.log(counter);
  window.onload = function() {
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');

    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        if (counter === 0) {
          notif({
            type: "info",
            msg: "Test Message",
            width: 650,
            height: 99,
            multiline: true,
            position: "center",
            fade: true,
            //timeout: 3000,
            autohide: false,
            clickable: true
          });
          counter++;
          //console.log(counter);
        } else {
          return false;
        }
      });
    }
  }
	
</script>

Open in new window

0
Hello
I have a function that works as I want. However, I would like it to run just once to show a message. I have tried to set a var to 0 then inc the var using ++ in the for loop but whatever I try, it just keeps displaying.

I would be grateful if someone could help with this. Thanks

<script type="text/javascript">
  window.onload = function() {
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');

    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
    }
  };
</script>

Open in new window

0
I am using a jQuery tabs package (SolidTabs) to present several jQuery/BootStrap (BootGrid) Ajax forms on the same page. iframes are not an option. As its name implies, BootGrid displays a table of records, along with the ability to add a new record or edit an existing one, taking advantage of Ajax, using json and PHP.
I have not wanted to mess with the main js file. I'm thinking I should just be able to change the various HTML id's, and I should be fine. So far, that has not been successful.

My perhaps naive question is - other than using an iframe, is there some way of containing these separate grid forms so that I could use the same id assignments on the same page?
0

jQuery

16K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

Related Topics