1659303720
O plugin jQuery Select2 é fácil de adicionar no elemento <select>. Precisa chamar o método select2() no seletor para inicializar.
Se você adicionar select2 em uma classe ou elemento select e adicionar um elemento dinamicamente, select2 não será inicializado nesse elemento.
Neste tutorial, mostro como você pode inicializar select2 no elemento <select> HTML criado dinamicamente usando jQuery.
Estou carregando dados select2 usando jQuery AJAX no exemplo.
Estou usando users
a tabela no exemplo -
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Crie um config.php
para uma conexão de banco de dados.
Código concluído
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = ""; /* Password */$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
Crie um <select class="select2_el" >
elemento para inicializar select2 no carregamento da página e crie <div id="elements" >
um container para armazenar o <select >
elemento ao clicar no botão usando jQuery AJAX.
Código concluído
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
Crie ajaxfile.php
um arquivo para lidar com solicitações AJAX.
Lidar com dois pedidos -
$request == 1
então retornar dados para select2.Verifique se searchTerm
é POST ou não. Se não for POST, busque todos os registros da users
tabela, caso contrário, use o valor POST para pesquisar no name
campo na users
tabela para buscar registros.
Faça um loop nos registros buscados e inicialize o $data
Array com as chaves id
e . text
Passe $row['id']
na id
chave e $row['name']
na text
chave.
Matriz de retorno $data
no formato JSON.
$request == 2
então retornar <select class="select2_el" >
elemento.Código concluído
<?php
include 'config.php';
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
Criar initailizeSelect2()
função para inicializar select2()
em class="select2_el"
. Use AJAX para carregar dados select2.
Chame initailizeSelect2()
a função no estado pronto do documento.
Defina o evento de clique em #btn_add
. Envie a solicitação POST AJAX para 'ajaxfile.php'
o arquivo para adicionar o <select >
elemento #elements
anexando o response
in #elements
.
Novamente chame a initailizeSelect2()
função para reinicializar o select2 em class="select2_el"
.
Código concluído
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
Você precisa reinicializar select2 no elemento dinâmico.
No exemplo, criei o elemento <select > usando jQuery AJAX e inicializando-o em classe. Você pode seguir o mesmo caminho para inicializar select2 se não estiver criando um elemento usando jQuery AJAX.
Você pode inicializá-lo no id do elemento em vez da classe se estiver obtendo o id.
Fonte: https://makitweb.com
1659303720
O plugin jQuery Select2 é fácil de adicionar no elemento <select>. Precisa chamar o método select2() no seletor para inicializar.
Se você adicionar select2 em uma classe ou elemento select e adicionar um elemento dinamicamente, select2 não será inicializado nesse elemento.
Neste tutorial, mostro como você pode inicializar select2 no elemento <select> HTML criado dinamicamente usando jQuery.
Estou carregando dados select2 usando jQuery AJAX no exemplo.
Estou usando users
a tabela no exemplo -
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Crie um config.php
para uma conexão de banco de dados.
Código concluído
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = ""; /* Password */$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
Crie um <select class="select2_el" >
elemento para inicializar select2 no carregamento da página e crie <div id="elements" >
um container para armazenar o <select >
elemento ao clicar no botão usando jQuery AJAX.
Código concluído
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
Crie ajaxfile.php
um arquivo para lidar com solicitações AJAX.
Lidar com dois pedidos -
$request == 1
então retornar dados para select2.Verifique se searchTerm
é POST ou não. Se não for POST, busque todos os registros da users
tabela, caso contrário, use o valor POST para pesquisar no name
campo na users
tabela para buscar registros.
Faça um loop nos registros buscados e inicialize o $data
Array com as chaves id
e . text
Passe $row['id']
na id
chave e $row['name']
na text
chave.
Matriz de retorno $data
no formato JSON.
$request == 2
então retornar <select class="select2_el" >
elemento.Código concluído
<?php
include 'config.php';
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
Criar initailizeSelect2()
função para inicializar select2()
em class="select2_el"
. Use AJAX para carregar dados select2.
Chame initailizeSelect2()
a função no estado pronto do documento.
Defina o evento de clique em #btn_add
. Envie a solicitação POST AJAX para 'ajaxfile.php'
o arquivo para adicionar o <select >
elemento #elements
anexando o response
in #elements
.
Novamente chame a initailizeSelect2()
função para reinicializar o select2 em class="select2_el"
.
Código concluído
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
Você precisa reinicializar select2 no elemento dinâmico.
No exemplo, criei o elemento <select > usando jQuery AJAX e inicializando-o em classe. Você pode seguir o mesmo caminho para inicializar select2 se não estiver criando um elemento usando jQuery AJAX.
Você pode inicializá-lo no id do elemento em vez da classe se estiver obtendo o id.
Fonte: https://makitweb.com
1659311100
El complemento Select2 jQuery es fácil de agregar en el elemento <select>. Necesita llamar al método select2() en el selector para inicializar.
Si agrega select2 en una clase o elemento seleccionado y cuando agrega un elemento dinámicamente, entonces select2 no se inicializa en ese elemento.
En este tutorial, muestro cómo puede inicializar select2 en un elemento HTML <select> creado dinámicamente usando jQuery.
Estoy cargando datos select2 usando jQuery AJAX en el ejemplo.
Estoy usando users
la tabla en el ejemplo:
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Cree un config.php
para una conexión de base de datos.
Código completado
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = ""; /* Password */$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
Cree un <select class="select2_el" >
elemento para inicializar select2 en la carga de la página y cree <div id="elements" >
un contenedor para almacenar <select >
el elemento al hacer clic en el botón usando jQuery AJAX.
Código completado
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
Crear ajaxfile.php
archivo para manejar solicitudes AJAX.
Manejar dos solicitudes:
$request == 1
luego devuelve datos para select2.Compruebe si searchTerm
es POST o no. Si no es POST, obtenga todos los registros de users
la tabla; de lo contrario, use el valor POST para buscar en el name
campo de la users
tabla para obtener registros.
Haga un bucle en los registros obtenidos e inicialice $data
Array con las teclas id
y . text
Pase $row['id']
en id
clave y $row['name']
en text
clave.
Retorna $data
Array en formato JSON.
$request == 2
entonces devuelve el <select class="select2_el" >
elemento.Código completado
<?php
include 'config.php';
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
Crear initailizeSelect2()
función para inicializar select2()
en class="select2_el"
. Use AJAX para cargar datos select2.
Función de llamada initailizeSelect2()
en estado de documento listo.
Definir evento de clic en #btn_add
. Envíe la solicitud AJAX POST al 'ajaxfile.php'
archivo para agregar <select >
el elemento #elements
agregando el response
archivo #elements
.
Vuelva a llamar a la initailizeSelect2()
función para reiniciar select2 en class="select2_el"
.
Código completado
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
Debe reiniciar select2 en el elemento dinámico.
En el ejemplo, creé el elemento <select> usando jQuery AJAX e inicializándolo en clase. Puede seguir la misma forma de inicializar select2 si no está creando un elemento usando jQuery AJAX.
Puede inicializarlo en la identificación del elemento en lugar de la clase si está obteniendo la identificación.
Fuente: https://makitweb.com
1592206043
Are You Looking To Hire a jQuery Programmer?
HourlyDeveloper.io, a leading jQuery application development company, can help you build interactive front-end solutions to leapfrog the digital race. So in case, you plan to Hire Dedicated Jquery Developer, you just have to contact us.
For More Information:- https://bit.ly/3f9flt8
#hire dedicated jquery developer #jquery programmer #jquery application development company #jquery developer #jquery #jquerydevelopment
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1620793161
In this post I will show you how to check password strength using jQuery, here I will check whether password strength is fulfill min character requirement or not.
I will give you example how to check password size using javascript and jQuery password strength. password is most important part of authentication many times you can see error message like enter valid password or password must be at least 6 character etc. So, here we are check password using jquery.
#jquery #how to check password strength using jquery #validation #how to check password size using javascript #jquery password strength #jquery password validation