jQuery

17K

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

I am storing image names in an array from DB and then encode it with json encode function to receive it in my ajax success method:

Here is the code"

$sql_gallery = "SELECT * FROM map_projects_gallery ";		
$gallery_result = mysqli_query($conn, $sql_gallery);
while( $gallery_row = mysqli_fetch_assoc($gallery_result) )
{					
$gallery_image_name[] = $gallery_row["img_name"];			
}		

echo json_encode(array("map_gallery" =>$gallery_image_name ));		

Open in new window



Note: In ajax success function it returns all the image names. Now I want to display all images in a div and then later display them in a slider.


And here is my Code of jQuery Ajax
jQuery.ajax({
	url:"project.php",
	type: "POST",	
	data:  {"country_id":country_id,"lang_name":langname_val,"node_id":node_id,"fullurl":'<?php echo base_path();?>'},
	dataType: "json",								
	success: function(data)
	{
		alert(data.map_gallery);
		jQuery('#project-list').html(data.message1);  
	        jQuery('#paginations').html(data.message_2); 
		  
		
		  ///jQuery('.pr-cont-gallery').html('<img src=files/'+project_details.project_image+' width=200px>');	  
		  
		  jQuery('.pr-cont-gallery').append('<img src="' + data[0].map_gallery + '" />');

		  
		  data.forEach(function (data) {
				jQuery('.pr-cont-gallery').append('<img src="aaaaa.jpg" />');
		   });
	},
  }); 

Open in new window


Problem:  I am unable to display all images separately in a div. Need help to fix this issue
0
Cloud Class® Course: Microsoft Windows 7 Basic
LVL 12
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

I have a right click function working and firing on right click.

 function setUpClickListener(map) {
        // Attach an event listener to map display$()
        // obtain the coordinates and display in an alert box.
        map.addEventListener('tap', function (evt) {
            var coord = map.screenToGeo(evt.currentPointer.viewportX,
                evt.currentPointer.viewportY);

            //  createContextMenu(map);
         //   alert('New at ' + Math.abs(coord.lat.toFixed(4)) +
            //  ((coord.lat > 0) ? 'N' : 'S') +
          //   ' ' + Math.abs(coord.lng.toFixed(4)) +
            // ((coord.lng > 0) ? 'E' : 'W'));
        });
    }

Open in new window

How do I make the function above declare a dynamic jquery context menu and then popup like the first command below, the second is how to declare the menu.

$(function(){
    // make button open the menu
    $('#activate-menu').on('click', function(e) {
        e.preventDefault();
        $('.context-menu-one').contextMenu();
        // or $('.context-menu-one').trigger("contextmenu");
        // or $('.context-menu-one').contextMenu({x: 100, y: 100});
    });

    $.contextMenu({
        selector: '.context-menu-one', 
        trigger: 'none',
        callback: function(key, options) {
            var m = "clicked: " + key;
            window.console && console.log(m) || alert(m); 
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
            "copy": {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: function($element, key, item){ return 'context-menu-icon context-menu-icon-quit'; }}
        }
    });
});

Open in new window

0
Hi Experts,

Can anyone tell me why my loop at the end of the script is not executed? I think something to do with length?

function translate(){
    
    var lbls = {
        'logo' : {
            'selector' : '',
            'english' : '',
            'ta' : '',
            'zh' : ''
        } ,
        'office' : {
            'selector' : '.footer-contact-detail-section '
                       + '.col-md-4:nth-child(1) h6',
            'prop' : 'text',
            'english' : 'Office',
            'ta' : 'Office_ta',
            'zh' : 'Office_ma'
        } ,
        'cell' : {
            'selector' : '.footer-contact-detail-section '
                       + '.col-md-4:nth-child(1) h4',
            'prop' : 'text',
            'english' : 'Cell',
            'ta' : 'Cell_ta',
            'zh' : 'Cell_ma'
        } ,
        'book' : {
            'selector' : '.footer-contact-detail-section '
                       + '.col-md-4:nth-child(3) h4 a',
            'prop' : 'text',
            'english' : 'Book 30 mins <br> FREE consultation',
            'ta' : 'Book <br> ta',
            'zh' : 'Book <br> ma'
        }
    };
    
    var lang = jq('#lang_choice_polylang-2').val();
        
    if (lang !== 'en'){
        
        var i;
        for (i = 0; i < lbls.length; i++){
            if (lbls[i]['prop'] === 'text'){
                console.log(lbls[i][lang]);
            }
        }
    }
    
}

Open in new window

0
How do i prevent double click on checkbox ?

 propCheck.one('change', actProp);

Open in new window


i have a few of these to trigger functions but how do i prevent double click.  one works but it means i cant reuse that checkbox until i refresh .

any tips
0
Im trying to take a array take the first value - convert into a string than output that value, and than do it for the rest of the value one after each other.

code -

for(var i = 0; i < response.data.length; i++){       
       
           var upperRes = response.data.toString();
   
        console.log(upperRes);
      

       }//for

Open in new window


for example array equals  ["POSITION", "FIRST_NAME"]

i want the result from the for loop to be like below in the console.

POSITION

FIRST_NAME

any tips ?
0
function actProp() {
      
     var isChecked = $(this).is(":checked");
     var propChk = "#" + $(this).attr('name');
     var chkCon = "#" + $(this).attr('class'); 
     var chkState = $(this).attr('id'); 
     var chkVal = "#" + $(this).val();
     

     if(isChecked) {  
        chkStateCollection.push(chkState); 
        var index = chkStateCollection.indexOf(chkState);
        console.log(chkStateCollection);
        console.log(index);
       $(propChk).fadeIn(1000);
       $(chkCon).fadeIn(1000);
         $(chkVal).fadeOut(1000); // fades out the checked box
        
         disCheck = $('#checked-list').find('input').each(function(){});
          disCheck.on('change', disProp);
         

        $('#subaction').val("setChkState");
        
        
        
     //  var data = $('#subaction').serialize();

           $.ajax({
                type: "POST",
                url: 'controllers/contacts.ajax.php',
                dataType: 'json',
                data: { subaction : "setChkState", chkStateCollection : chkStateCollection},
            }).success(function (response) {
            

              console.log(response)

                
            }).error(function (response) {
                console.log("error");
            });
       //addChkState();
       return false;
       } 
     else {  
        var index = chkStateCollection.indexOf(chkState);
        chkStateCollection.splice(index, 1);
       



         event.stopPropagation();
     

Open in new window

0
Here is the ajax call

function showCustomProps(){
    
    $('#subaction').val("getCustomProperties");
    var data = $('#subaction') ;
  
  
    $.ajax({
        type: "POST",
        url: 'controllers/contacts.ajax.php',
        data: data,
    }).success(function (response) {
      
        
        
        console.log(response);
        
    }).error(function (data) {
        console.log("erro customProps");
    });
    
} //showCustomProps

Open in new window


this is triggered on load.

to run this code -

$stmt = new Database();

				$query = "SELECT cp.id, cp.name, cp.field_type 
							FROM custom_properties cp
							WHERE cp.client_id = :clientID AND cp.viewable='1' AND cp.type = '1'
							ORDER BY cp.id DESC";
				$stmt->query( $query );
				$stmt->bind( ':clientID', $clientId);
		     	$stmt->execute();
				$demo1 = $stmt->fetchAll();

				foreach($demo1 as $customResult){
					$cusData['propertyId'] = $customResult['id'];
					$cusData['propertyName'] = $customResult['name'];
					$cusData['propertyType'] = $customResult['field_type'];
				

			

				}//customresult

						$response = array(
							'subresult' => 'customProps success',
							'data' => $cusData
						
							
						);

		break;

Open in new window



Now the issue is that it is returning null.  but if i change fetchAll to all it returns a row from the database, i need this foreach to fetch all records not just the first one. if i return demo1 instead of customResult i can see there is two records, Please note i can only see this data if i use all() and when i use fetchAll it returns null.
0
Array =

"<select style ='width:100%;' class='formInput' name='property'2527'' id='property'2527''><option value=''>- select -</option>"
1
:
"<option value='test1' >test1</option>"
2
:
"<option value='test2' >test2</option>"
3
:
"<option value='test3' >test3</option>"
4
:
"</select>"

Open in new window


so i then append to my html

$("#custom-properties").append(properties.custom);

Open in new window



but the output structure is incorrect ?

html structure
any hints
0
Quite a puzzling issue,  so i am trying to get the inputs of checkboxes, which works fine but when i want to get a 2nd check from a different div it cannot be found but can later down the line.

code -

var propCheck = $('input', '#default-checked-list , #checked-list-container ').each(function(){}); // cannot find checked-list-container here
     var chkStateCollection = [];
       
       

    
      
    propCheck.on('change', actProp);

    function actProp() {
      
     var isChecked = $(this).is(":checked");
     var propChk = "#" + $(this).attr('name');
     var chkCon = "#" + $(this).attr('class'); 
     var chkState = $(this).attr('id'); 
     var getConID = "#" + $(this).val();
     
     
 
     if(isChecked) {  
        chkStateCollection.push(chkState); 
        var index = chkStateCollection.indexOf(chkState);
        console.log(chkStateCollection);
        console.log(index);
        var disProp = $('input', '#default-checked-list , #checked-list-container ').each(function(){}); // but can find checked-list-container here
         console.log(propCheck);
        console.log(disProp);
         
        
         
       $(propChk).fadeIn(1000);
       $(chkCon).fadeIn(1000);
       $(getConID).fadeOut(1000);
         
         console.log(getConID);
        
         

        $('#subaction').val("setChkState");
        
        
        
     //  var data = $('#subaction').serialize();

           $.ajax({
                type: "POST",
          

Open in new window

0
When I check on Checkbox then assign margin value which in Mysqli, should be added with amount
How to do?

0
Cloud Class® Course: Certified Penetration Testing
LVL 12
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

I have developed a website using php 7, jQuery and ajax. I have had a few people mention that the website does not work on Internet explorer. There has been no mention of what version but if they said Internet explorer then it sounds like prior to Edge. Apparently just a blank screen appears instead of the actual website. I am running a mac so don't have internet explorer to check myself. What would the best solution be? To either redirect them to a page that requests that they use a more modern browser or.... ?
0
Im trying to go into a container and take the inputs and change their ids of all of them. but not sure how this is my first try.

if(properties.clientzone == "") {

         
            $("#default-location-props").append(properties.location);
            $("#default-personal-properties").append(properties.personal);

            $("#left-contact-list").append(leftFormProps);
            var testdata = $('input', '#left-contact-list').each(function(){});
            var testinput = testdata.attr("id");
            console.log(testinput);

            for(var b = 0; b < leftFormProps.length; b++){
                testdata.attr("id", "test");
            }
            console.log(testinput);

            $("#checked-list").append(properties.checklist);
            $("#custom-properties").append(properties.custom);
        } else {
    
            $("#default-location-props").append(properties.location);
            $("#default-personal-properties").append(properties.personalUS);
      
            $("#checked-list").append(properties.checklist);
            $("#custom-properties").append(properties.custom);
        }

Open in new window


leftFormProps is an array with the contents of the left form which is just labels and inputs and im trying to go into this container once populated and change the ids.
0
if(isChecked) {  
               
              console.log("checked");


              $('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                if( _for.length ) {
                      var emptyInput = $("#"+ _for).val();
                      if( emptyInput == "" ) {
                                  console.log(emptyInput)
                                  $("#"+ _for).fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                }
           });

          
            } 
            else {  
             
            
                console.log("unchecked")

                $('#default-personal-properties').find('input, label').each(function(){
                    if($(this).val() == ""){
                        console.log("showing fields");
                        $(this).fadeIn();
                    }
               });


                 
            }

Open in new window


So this code above works because i tested it on hard coded inputs, so i alter the calls to my inputs and it wont fade out, now i think i know why is because my data aint st8 forward instead the data is loaded in dynamically so JQ dont think it exists when it already is so how do i get it to fade in and out ? this is a checkbox to handle blank input fields.
0
is there any smarter way i can do this ?  -

$('#default-personal-properties').find('input, label').each(function(){
                   if($(this).val() == ""){
                       console.log("field is blank");
                       $(this).fadeOut();
                   } else {
                       console.log("field is not blank");
                   }
              });

Open in new window


what i am doing here is searching a container with inputs and checking if they have a value, if they dont i want them and their label to fadeout but the issue i am having is the label is hidden on those who do have values, ino why but i cant think of a way round it so when i hide blank fields the label dont fade on non blank fields .

html input setup -


<div id = 'firstname' class=' col-md-4'>
								<label class=' control-label' for='textinput'>First Name</label>                 
								<input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='".$v_item['FIRST_NAME']."' > 
								</div>

Open in new window


any tips ?
0
JQ onclick not triggering or any event on any inputs within this container.


So i have a container with inputs now im trying to test a click event on these inputs but it isnt working and no errors and i used click hundreds of times and never had this issue,


so really simple -

$(document).ready(function() {
    $("#contact-personal-fname").click(function () {
      alert("Hello!");

    });
  });

Open in new window


which refers to this one -

<div id = 'firstname' class=' col-md-4'>
                      <label class=' control-label' for='textinput'>First Name</label>                 
                      <input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='".$v_item['FIRST_NAME']."' > 
                    </div>

Open in new window


now this isnt hard coded in, it actually been passed from ajax and appended like so .

   var arrayJson = JSON.stringify(response);
        var properties = JSON.parse(arrayJson);
 $("#default-personal-properties").append(properties.personal);

Open in new window


how it looks in its array . -

personal
:
Array(16)
0
:
"↵								<div id = 'firstname' class=' col-md-4'>↵								<label class=' control-label' for='textinput'>First Name</label>                 ↵								<input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='Tim' > ↵								</div>↵						"
1
:
"↵↵						"

Open in new window

0
ASP.Net MVC 5

I am trying to fetch the result from Jquery to my controller.

However, in my controller - ActionResult is not invoking.   What could be the reason ?

        [HttpGet]
        public ActionResult ActionName(string id)
        {
            // do something
            var vm = id;
            return View(vm);
        }

JQuery Syntax :


   $('button').click(function () {
        var btn = $(this).attr('id');

        alert(btn);

        $.ajax({
            type: 'GET',
            url: '@Url.Action("ActionName", "ControllerName")',
            data: { id: btn },
            success: function (result) {
                // do something
            }
        });
    });
0
I want to delete particular row when I click on delete icon ?
Append row working fine when I click on '+' sign


JavaScript Code :
<script type="text/javascript">
  var count=2;
  function addnewrow()
  {
    
    var div = '<div class="row col-md-12" id="row'+count+'">'+
    '<div class="col-md-2">'+
        '<div class="form-group">'+
          '<label for="p_type"><font color="red">*</font>Product Type</label>'+

          '<select id="p_type" name="p_type" onChange="getCatg(this.value,'+count+');" class="form-control" tabindex="1" required>'+
            '<option>Select Product Type</option>'+
            '<option value="Goods">Goods</option>'+
            '<option value="Service">Service</option>'+
          '</select>'+
        '</div>'+
    '</div>'+

    '<div class="col-md-3">'+
      '<div class="form-group">'+
        '<label for="c_name"><font color="red">*</font>Sub-Category</label>'+
        '<select name="c_id" id="c_id_'+count+'" onChange="getProd(this.value,'+count+');" class="form-control" required>'+
          '<option>Select Sub-Category</option>'+
        '</select>'+
      '</div>'+
    '</div>'+
'</div>'+

'<div class="col-md-12">'+
  '<div class="table-responsive">'+
'<table  class="table table-bordered table-hover">'+
          '<thead>'+
            '<tr>'+
              '<th width="20%">Item Details</th>'+
              '<th width="20%">Vendor Name</th>'+
              '<th width="20%">Quantity</th>'+
 

Open in new window

0
How to pass Jquery variable value to c# mvc?

I need to fetch the value of the variable btn in mvc code behind.

$("button").click(function ()
    {
        var btn = this.id;
        if (btn == "previewButton")
        {
          alert(btn);

        }
  }

Open in new window


Based on the variable value (Submit Button (or) Preview Button), my model will have Required validation on certain fields.
0
How to fetch HTML Input Id in code behind ASP.Net MVC ? Either on Controller or on Model ?

 view / .cshtml 

<button type="submit" id="previewButton" >Preview</button>

JQuery : - This will not be in use.

$("button").click(function ()
    {
        var btn = this.id;
          alert(btn);
   }

In Controller :

[HttpPost]
        public ActionResult New(MyViewModel viewModel, string clickedButton)
        {
            
            var vm = clickedButton;
            return View(vm);
        }

- MyViewModel
 public string clickedButton { get; set; }

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017
LVL 12
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

How to handle Required field validation in Jquery for radiobuttons in asp.net mvc?

Currently, I am handling it in the Model
view \ create.cshtml page

   
<div class="col-sm-3 checkbox-inline">
                        @Html.RadioButtonFor(model => model.IsDateChanged, 1, new { @Id = "IsDateChangedYes" })
                        <label class="hthin" for="IsDateChangedYes">Yes</label>
                        @Html.RadioButtonFor(model => model.IsDateChanged, 0, new { @Id = "IsDateChangedNo" })
                        <label class="hthin" for="IsDateChangedNo">No</label>
                        <span asp-validation-for="IsDateChanged" class="text-danger"></span>
                    </div>

Open in new window



viewmodel \ mymodel.cs

 [Required(ErrorMessage = "Required")]
        [Display(Name = "1. Have there been any changes in the date?")]
        public int? HasDateChanged { get; set; }

Open in new window

0
I am using kendo's "Expand and Collapse All Detail Rows in Grid" for one of my pages.  Here is the page that I am using as example : https://docs.telerik.com/kendo-ui/knowledge-base/grid-how-to-expand-and-collapse-details-rows.

Everything works as expected for me except expand and collapse button. I have made some changes to javascript in order to pull the data from my database. Pasted below is my code.

I am getting an error on this line when i click the expand button : this.expandRow(this.tbody.find("tr.k-master-row").first());
Error :  uncaught typeerror cannot read property 'find' of undefined

$(document).ready(function () {
    $("#startDate").kendoDatePicker();

    $("#endDate").kendoDatePicker();


          var element = $("#grid").kendoGrid({
            dataSource: {
                transport: {
                    read: {
                        url: "/Test/DashboardParentGrid",
                        type: "POST",
                        complete: function () { $(".k-grid-pager").show(); }
                    }
                
      },
                pageSize: 10,
                schema: {
                    model: {
                        fields: {
                           // isOfac: { type: "boolean" },
                           totalCases: { type: "number" },
                           avghandletime: { type: "int" },
                           team: { type: "string" },
                           qcpass: { type: "number" },
              

Open in new window

0
Hi Guys,
Let me explain what I would like to do:
I have a button, input type="file" and dialogbox(I didn't post the full dialog as it is long so just get the idea)
Here is my html:
//click button
 <a class="btn btn-default" id="AddAttachmentId">add attchment</a>
//uploadfile
    <input type="file" id="FileUploadForAttach" name="FileUploadForAttach" runat="server" multiple="multiple" style="display: none" />
//dialog
<div id="WriteAttachmentName" class="modal fade" data-keyboard="false" tabindex="-1" role="dialog" aria-hidden="true"></div>

Open in new window


Now what I want to do is:
1. when user click on the button the code below fire (which works):
2. after user choose the file click k I would like to show the bootstrap dialog.
issue:
the file dialog and bootstrap dialog  pop up together.

 $("#AddAttachmentId").on('click', function () {
        debugger;
        var Fileup = $('#FileUploadForAttach');
        Fileup.trigger("click")
        $('#WriteAttachmentName').modal('show').draggable({ handle: ".modal-header" });
        return false;
    });

Open in new window

0
So here is my problem. i have a JS function that checked for check event and takes the attr of these check boxes and store them for later use, this function controls outputs for check condition of checkboxes, what i am trying to add to the function is to take the id attr of the checkboxes and store them into an array to be passed on during a condition. my issue is im not sure how to do this as multiple attempt failed any hints.

my function as follows -

function actProp() {
      
     var isChecked = $(this).is(":checked");
     var propChk = "#" + $(this).attr('name');
     var chkCon = "#" + $(this).attr('class'); 
     var chkState = $(this).attr('id'); 
     var chkStateCollection = [];

   chkStateCollection.push(chkState);
     if(isChecked) {   
        console.log(chkStateCollection);
       $(propChk).fadeIn(1000);
       $(chkCon).fadeIn(1000);
  
       //addChkState();
       
      
      
       
       return false;
       } 
     else {  
         event.stopPropagation();
        $(propChk).fadeOut(1000); 
        $(chkCon).fadeOut(1000);       
       }
       
    }

Open in new window

0
I have setup a Sphinx search which uses jQuery AutoComplete functionality to display search suggestions. Auto Suggestions are coming from a database table.
What is the best way to generate AutoComplete Suggestions. Currently I am adding keywords manually in a table.

I want to display common words from news titles and descriptions. As news are added on daily basis what is the best way to
generate search suggestions in some best way.

PS: I have heard about META Fones. Is it related to AutoComplete Search?
0
Hi team,

How to validate square bracket '[ and ]' in JavaScript (regular expression).

I have a textbox having value like this. So, I need a regular expression which will tell me square bracket is present in the textbox or not.

If there is a square bracket present in the textbox it will give me a error message.

[ABC  ESS080820183171][CTK  ESS080820189505][TROUS  ESS080820183485][SIMINESS  ESS080820184038][RAMMMM  ESS080820185998]
0

jQuery

17K

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