PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label jquery-select2. Show all posts
Showing posts with label jquery-select2. Show all posts

Thursday, September 8, 2022

[FIXED] How to set selected value of jQuery Select2?

 September 08, 2022     ajax, javascript, jquery, jquery-select2, php     No comments   

Issue

This belong to codes prior to Select2 version 4

I have a simple code of select2 that get data from AJAX.

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

UPDATE:

The HTML code:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2 programmatic access does not work with this.


Solution

To dynamically set the "selected" value of a Select2 component:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

Where the second parameter is an object with expected values.

UPDATE:

This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

Example:

$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});

Thanks to @NoobishPro



Answered By - An Phan
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, June 29, 2022

[FIXED] How to add Select2 to a smarty template in Shopware 5 plugin?

 June 29, 2022     jquery-select2, shopware, smarty     No comments   

Issue

I would like to add select2 to a smarty template in a shopware 5 plugin, in order to be able to type and search for a value in the dropdown. I was searching for it but found nothing relevant. As I see, there is only a standard <select> which is a html select, and {html_options} there is no way to type and search for what you are looking for in the dropdown, right? Is it possible to add select2 to smarty? If yes, could you please pont me to the rigth direction? If it's not possible or too complicated, what would be a better alternative? Is it possible in Shopware 6? (I wanted to ask this question actually on stack exchange, but I can't...)


Solution

Unfortunately you did not mention what you try so far.

I believe you have to add the Javascript resources as in https://select2.org/getting-started/installation and add the .select2() call in the on ready.

The HTML of the select can stay the same - the select2 script will transform this.



Answered By - Alex
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] How to use Select2 with JSON via Ajax request?

 April 19, 2022     javascript, jquery-select2, json, laravel     No comments   

Issue

My Select2 3.4.5 is not working with JSON data.

Here is my input box on HTML:

<input class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />

…and my JavaScript

$(".itemSearch").select2({
    placeholder: "Search for an Item",
    minimumInputLength: 2,
    ajax: {
        url: "/api/productSearch",
        dataType: 'json',
        quietMillis: 100,
        data: function (term, page) {
            return {
                option: term
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total;
            return {
                results: data.itemName,
                more: more
            };
        }
    },
    formatResult: function (data, term) {
        return data;
    },
    formatSelection: function (data) {
        return data;
    },
    dropdownCssClass: "bigdrop",
    escapeMarkup: function (m) {
        return m;
    }
});

I made an API with Laravel 4 which returns a value whenever I type anything on my text box.

Here's the result if I type "test" on my text box:

[{"itemName":"Test item no. 1","id":5},
{"itemName":"Test item no. 2","id":6},
{"itemName":"Test item no. 3","id":7},
{"itemName":"Test item no. 4","id":8},
{"itemName":"Test item no. 5","id":9},
{"itemName":"Test item no. 6","id":10},
{"itemName":"Test item no. 7","id":11}]

I can't add the result to my Select2 dropdown. I think formatSelection and formatResult are causing the problem because I don't know what parameter should be placed on it. I don't know where to get those parameters like container, object and query and the values it should be returning, or is my JSON response is wrong?


Solution

Here you have an example

$("#profiles-thread").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: URL,
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.completeName,
                        slug: item.slug,
                        id: item.id
                    }
                })
            };
        }
    }
});

It's quite easy



Answered By - Tolo Palmer
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 19, 2022

[FIXED] how to set default item in Select2 on Yii2

 March 19, 2022     jquery-select2, jquery-select2-4, ui-select2, yii, yii2     No comments   

Issue

how to set default item in Select2 on Yii2

The initSelection method of Select2 3.5.x plugin is obsolete/removed. New initValueText property is been provided with the Select2 widget to cater to this (e.g. for ajax based loading).

but initValueText dont work!!!

<div class="col-xs-12">
            <?php
            $categories = [5 => 'test1', 7=> 'test2', 8=> 'test3'];
            echo Select2::widget([
                'initValueText' => $categories,
                'model' => $modelKani,
                'name' => 'Kani',
                'id' => 'Kani',
                'data' => $data,
                'showToggleAll' => false,
                'options' => [
                    'placeholder' => 'Insert Item',
                    'multiple' => true,
                    'allowClear' => true,
                    'minimumInputLength' => 2,
                    'dir' => 'rtl'
                ],
            ]);
            ?>
    </div>

result $data:

Array
(
    [5] = test1
    [7] = test2
    [8] = test3
)

Solution

work with this:

'value' => [5, 10]

item id 5,10 from $data

Doc:

http://demos.krajee.com/widget-details/select2#usage-tags



Answered By - user3770797
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, March 14, 2022

[FIXED] Loading Select2 statement data with onclick AJAX call

 March 14, 2022     ajax, codeigniter, jquery, jquery-select2, php     No comments   

Issue

Currently I'm using a controller to fetch all my data and placing it in a foreach statement in my view class. So whenever the page is loaded, it executes this function. To achieve this I used something like this:

Controller Class:

$add['sources']= $this->contacts_model->get_array();

View class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
          <option value="">Select</option>
          <?php foreach($sources as $source): ?>
          <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
          <?php endforeach; ?>
   </select>

But now I want the page to load faster, so for that I want to load the dropdown only when the user has clicked on that particular select2 statement. I've tried the following code to get the select2 variables with the select 2 functionality of getting an input text with dropdown, but none of them work. It just brings up a normal dropdown that loads when my page loads.

View Class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
              <option value="">Select</option>
              <?php foreach($sources as $source): ?>
              <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
              <?php endforeach; ?>
</select>

$(document).ready(function(){
  $('#contact_source').on('click', function(e) {
    $("#contact_source").select2({
      minimumInputLength: 2,
      tags: [],
      ajax: {
          url: "<?php echo site_url('contacts/add'); ?>/",
          dataType: 'json',
          type: "GET",
          delay : 50,
          data: function (data) {
              return {
                sources: data.sources
              };
          },
          results: function (data) {
              return {
                  results: $.map(data, function (item) {
                      return {
                          text: item.sources,
                          id: item.id
                      }
                  })
              };
          }
      }
  });
})
});

Solution

Remove select2 in <select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>

and remove also $('#contact_source').on('click', function(e) {

And I recommend jQuery Autocomplete. https://jqueryui.com/autocomplete/#remote



Answered By - Raphael
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] Laravel pluck but combining first name + last name for select

 March 11, 2022     eloquent, jquery-select2, laravel, laravel-5     No comments   

Issue

Using select2 with a Laravel / Vue project and need to return JSON in the following format:

[
    { id: 0, text: 'enhancement' },
    { id: 1, text: 'bug' }
]

In Laravel I know I can use pluck to create my list data e.g. for customers:

$customers = Customer::pluck('id', 'first_name');

But Want to return the id and first name + last name as a single name.

How can I do this?


Solution

Have you tried using Accessors?

https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

I have not tested it but this could work:

add this to your Customer Eloquent Model:

    public function getFullNameAttribute()
    {
       return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
    }

and then try:

UPDATED pluck on accessor will only work on a collection. If you try Customer::pluck('id', 'full_name') it will not work since there is no db column named full_name, therefore you must use Customer::all()->pluck('full_name', 'id')

$customers = Customer::all()->pluck('full_name', 'id');
  • as a side note, for performance it is probably better to do Customer::all(['id', 'first_name', 'last_name'])->pluck(...) so that we don't pull unnecessary columns from the db.

Hope this helps.

Updated Date:- 26th Aug, 2021 If we use computed Attribute accessor functionality, then mind it one important thing...

Laravel Accessor functionality works after the Data fetched from DataBase. So we have to declare "pluck(accessorName)" at the end of Query....

For Example:-

Wrong Methods:-

$data = Model::pluck('full_name','id)->get(); 
$data = Model::pluck('full_name','id)->all();

in above two queries if you does not have full_name field in DataTable you will get Unknown column error

Right Methods:-

$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');

in above two queries it will works perfectly even if you doesn't have full_name field in DataTable



Answered By - dev7
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 8, 2022

[FIXED] Laravel Dusk - Call to a member function click() on array

 March 08, 2022     jquery-select2, laravel, laravel-dusk, php, testing     No comments   

Issue

I have a problem. When I try to run my dusk test it outputs this error:

1) Tests\Browser\NewPostTest::test_new_post
Error: Call to a member function click() on array

D:\xampp\htdocs\laravel_blog\tests\Browser\NewPostTest.php:32
D:\xampp\htdocs\laravel_blog\vendor\laravel\dusk\src\Concerns\ProvidesBrowser.php:67
D:\xampp\htdocs\laravel_blog\tests\Browser\NewPostTest.php:34

My testing method looks like this:

public function test_new_post()
    {
        $this->browse(function (Browser $browser) {
          $faker = Faker::create();
          $title = $faker->sentence();
          $slug = str_replace(' ', '-', $title);
          $browser->loginAs(User::find(2))
                  ->visit('/posts/create')
                  ->assertSee('Create New Post')
                  ->type('title', $title)
                  ->type('slug', $slug)
                  ->type('body', $faker->paragraphs(5, true))
                  ->select('category_id')
                  ->script('jQuery(".select2").val(["1","2"]).trigger("change");')
                  ->click('input[type=submit]#submit')
                  ->assertPathIs('/posts');
        });
    }

As you see I'm using select2 for my tags . Can anyone please tell me what I'm doing wrong?


Solution

You can't use chaining after script() because it returns an array instead of $this:

$browser->[...]
    ->script('jQuery(".select2").val(["1","2"]).trigger("change");')
$browser->click('input[type=submit]#submit')
    ->assertPathIs('/posts');


Answered By - Jonas Staudenmeir
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 19, 2022

[FIXED] select2 js empty value on load in select option

 February 19, 2022     jquery-select2, laravel-5     No comments   

Issue

I have implemented select2js in my project, In few cases when i load my page, an empty value is appending to my select input box. Can anyone help me out, what is the issue, I have added a image of it and My code is

{!! Form::select('searchSkillTools[]',[],(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:'', array('autocomplete' => 'off', 'class' => 'chosen-select','multiple'=>'multiple', 'id' => 'searchSkillTools-'.$randomId, 'placeholder' => '' ,'style' => 'height: auto !important')) !!}

$('#searchSkillTools-{{$randomId}}').select2({  
    ajax: {
        url: skillToolUrl,
        dataType: 'json',
        method:'get',
        delay: 250,//delay in response
        data: function (data) {
            return {
                search: data.term //search term
            };
        },
        /*option to transform the data returned by response into the format expected by Select2*/
        processResults: function (response) {            
            return {
                results:response
            };
        },
        cache: true
    }
});

enter image description here


Solution

This way will fix the bug:

(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:null



Answered By - Andy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 1, 2022

[FIXED] How to implement select2 in laravel

 February 01, 2022     html, javascript, jquery-select2, laravel, laravel-5     No comments   

Issue

I have simple input I would like to user select js select2js

Here is my input

<div class="form-group">

    <select class="js-example-basic-multiple form-control" name="states[]" multiple="multiple">
        <option value="AL">Alabama</option>
        ...
        <option value="WY">Wyoming</option>
    </select>

    <!-- Button trigger modal -->

</div>

in my app.blade.php (master) I have this

$(document).ready(function() {
    $('.js-example-basic-multiple').select2()
});

Now when I run my app I get this error

caught TypeError: $(...).select2 is not a function
at HTMLDocument.<anonymous> (create:420)
at j (jquery.min.js:1197)
at k (jquery.min.js:1203)

In console network both js and CSS for select2 are loaded

What is wrong with my code?


Solution

May be due to one of the following reason:

  • Your select2 JS is not added in right place, like you need to add it after jQuery
  • Other JS scripts might have throwing an error which causing all other JS scripts to breaks
  • Your jQuery version is not compatible with the select2 jQuery plugin
  • You may have multiple jQuery added for different jQuery plugin


Answered By - Azhar Rasheed
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing