Livewire Dom update break jquery plugin like Select2 .. etc - jquery-plugins

I'm facing an issue when livewire DOM update jquery plugin not work , jquery plugins breaks and not working . Kindly proper guid thanks

When select2, I solved the issue by doing the next
//in component
public $selectedElem;
public function hydrate()
{
$this->emit('select2Hydrate');
}
public function updatedSelectedElem($value)
{
dd($value);
}
//in blade
<select class="form-control select2_livewire" wire:model="selectedElem">
//.....
</select>
<script>
$(document).ready(function() {
window.loadSelect2 = () => {
$('.select2_livewire').select2().on('change',function () {
#this.set('selectedElem',$(this).val());
});
}
loadSelect2();
window.livewire.on('select2Hydrate',()=>{
loadSelect2();
});
}
</script>

Related

Can't Post TextArea value using WYSIWYG Editor in Razor Pages

I'm developing a .NET Core 3.1 Razor Pages Application. One of the Razor Pages within my app Posts the contents of a TextArea using AJAX. This works as expected, however, when I use CKEditor 5 https://ckeditor.com/ckeditor-5/ and turn the TextArea into a WYSIWYG Editor, I can no longer Post the values within the editor.
Please note, the CKEditor loads as expected and there are no errors when I use Developer Tools within Google Chrome.
PageModel
[BindProperty]
public InputModel Input { get; set; }
public PartialViewResult OnPostMyTestPartial()
{
//Some logic then return data for partial
}
public class InputModel
{
public int Id { get; set; }
public string Narrative { get; set; }
}
CSHTML
<form>
<!-- Other html -->
<textarea asp-for="Input.Narrative"></textarea>
<button class="btn btn-primary" id="load">Update</button>
</form>
JQuery
$(document).ready(function () {
$('#load').on('click', function (evt) {
evt.preventDefault();
$.post("/MyPage/Index?handler=MyTestPartial", $('form').serialize(), function (data) {
$("#myPartial").html(data);
});
});
ClassicEditor
.create(document.querySelector('#Input_Narrative'), {
toolbar: ['heading', '|', 'bold', 'italic', 'link']
})
.then(editor => {
window.editor = editor;
})
.catch(err => {
console.error(err.stack);
});
});
When I comment out the ClassicEditor code in my JQuery file so that the TextArea remains purely as a TextArea, I can see through the Developer Tools and debugging in Visual Studio that the value is Posted successfully:
However, when I make the TextArea into an editor using the CKEditor and attempt to Post data, the data is not posted.
Can someone please help?
Thanks.
You need to manually transfer the content of the editor to the form control:
$('#load').on('click', function (evt) {
evt.preventDefault();
$('#Input_Narrative').val(CKEDITOR.instances['Input_Narrative'].getData());
$.post("/MyPage/Index?handler=MyTestPartial", $('form').serialize(), function (data) {
$("#myPartial").html(data);
});
});
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/saving-data.html#manually-retrieving-the-data

Livewire Select2 Dynamic not updating public view

I am using a select2 component with wire:ignore and i want to update the select2 value dynamically after clicking a button. I set up this functionality with events and events work fine, so does the variable gets initialized as well. I am failing to update this public view of this select2.
my blade
<select class="select2-example form-control" id="subjects" wire:model.lazy="subjects" name="subjects">
</select>
#push('scripts')
<script>
$('#subjects').select2({
maximumSelectionLength: 1,
minimumInputLength:2,
tags: false,
placeholder: 'Enter Subject(s)',
.... // this all works great
});
$('#subjects').on('change', function (e) {
let data = $(this).val();
#this.set('subjects', data);
});
// my event listener and it is working as well
Livewire.on('editSubject', subject => {
console.log(subject);
#this.set('subjects', subject);
$('#subjects').val(subject);
$('#subjects').trigger('change'); //the public view doesn't get updated
})
</script>
#endpush
I so far tried with browser dispatch event as well. Nothing works. What would be the workaround for this? Any help is greatly appreciated.
in blade
<div class="col d-flex display-inline-block">
<label for="contact_devices">{{ __('Select Device') }}</label>
<select id="contact_devices" wire:model="selectedDevice" class="form-control contact_devices_multiple" multiple="multiple" data-placeholder="{{ __('Select') }}">
#foreach($devices as $device)
<option value="{{ $device->id }}">{{ $device->alias }}</option>
#endforeach
</select>
</div>
<script>
window.loadContactDeviceSelect2 = () => {
$('.contact_devices_multiple').select2({
// any other option
}).on('change',function () {
livewire.emitTo('tenant.contact-component','devicesSelect',$(this).val());
});
}
loadContactDeviceSelect2();
window.livewire.on('loadContactDeviceSelect2',()=>{
loadContactDeviceSelect2();
});
</script>
in component
public $selectedDevice;
protected $listeners = [
'devicesSelect'
];
public function devicesSelect($data)
{
dd($data);
$this->selectedDevice = $data;
}
public function hydrate()
{
$this->emit('loadContactDeviceSelect2');
}
Note: If some face the problem of real time validaiton while implementing the above mentioned solution as i have commented in the accepted answer above.
My Comments:
hey, I have implemented your solution its working great but there is
one problem, here is the scenario, I submit empty form and all the
validations gets triggered, when i start filling the form the error
starts to disappear but as soon as i change the select2 the validation
part $this-update($key, $value) function does not work. Can you please
tell me why real time validation is not working ? and how to fix it
please. thankyou – Wcan
Solution:
Use syncInput() function instead of assigning the value to country property. updated lifecycle hook will be trigerred automatically.
public function setCountry($countryValue)
{
// $this->country = $countryValue;
$this->syncInput('country', $countryValue);
}

Asp.NET MCV how to call a viewmodel function that performs a db connection on button click correctly?

I have a few viewmodels, which contains a few functions like:
public override string ToString()
{
return $"{M_IV_ID} {M_IV_INVOICEAMOUNT} {M_IV_MANDANT} {M_IV_TOTALAMOUNT} {M_IV_VEHICLE_PURCHASE} {M_IV_URGENT}";
}
And update / insert functionalities. All of them work. I wrote them separately from my Asp.NET project and tested them since I wanted to do my back end first.
Now I tried to use those functions in my Asp.NET application:
First I get Data from the db in my Controller:
M_IV_INVOICE invoice = QueryBuilder.GetFirstOrDefault(new M_IV_INVOICE(), #"WHERE M_IV_ID IN (75693)");
And pass it to my view:
public ActionResult Index()
{
return View(invoice);
}
Now I tried to use my toString() method just to see if it works:
<form id="formUpdate" runat="server">
<div>
<asp:button id="Button" class="btn btn-primary" runat="server">Update</asp:button>
</div>
</form>
#{
string MyFunction()
{
return Model.ToString();
}
}
#section Scripts
{
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
var test = "#MyFunction()";
console.log(test);
});
});
</script>
}
And if I do this, it works, and I get my model values printed in the browser console.
If I try to use my Update function instead of the toString() method:
public bool Update()
{
using (IDbConnection conn = ConnectionManager.GetConnection())
{
try
{
conn.Query(QueryBuilder.BuildUpdateForEntity(this, string.Format(" WHERE {0} = {1}", GetKey().Item1, GetKey().Item2)));
return true;
}catch(Exception e)
{
// TODO: Exceptionhandling
}
}
return false;
}
I get a Ora Exception right when the page loads, no button click performed:
Oracle.DataAccess.Client.OracleException: ORA-00936: missing expression
I struggle with understanding why, though.
The select I perform in my controller to get the data in the first place is working just fine, and as I said, if I print my model on button click, it works too.
What am I missing?
Edit:
It seems like the function is directly called while the eventhandler is added and since it has no data at the time, the ORA error is occurring.
But why? I don't understand this behavior.
Another Edit:
It has indeed something to do with the model isn't ready or something:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
setTimeout(() => { console.log("#MyFunction()") }, 3000);
});
});
</script>
I added the delay and no error on loading the page.
But that would be just a band aid, not a solution.
If someone has an idea how to prevent that behavior, I would appreciate it.
The #{}symbol is used to write server-side C# or VB code with HTML code, so in the javascript, when you use the #MyFunction() function, the Myfunction will execute. You could set a break point in the MyFunction and the button click event to check it, no matter using the ToString() method or the Update() method, they will work when the DOMContent Loaded. So, when use the Update() method, you will meet the missing expression error.
Based on your description, you want to do some action (call the server-side function/method) when user clicks the button, right? If that is the case, I suggest in the controller you can add the Myfunction and Update action methods, then, in the button click event, you can use JQuery get(), post() or Ajax method to call the action method, refer the following code:
Controller:
[HttpPost]
public JsonResult AjaxMethod(string name)
{
PersonModel person = new PersonModel
{
Name = name,
DateTime = DateTime.Now.ToString()
};
return Json(person);
}
and View Page:
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
#section Scripts{
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Test/AjaxMethod",
data: { name: $("#txtName").val() },
success: function (response) {
alert("Hello: " + response.name + " .\nCurrent Date and Time: " + response.dateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}

How to update div contents on 'onchange' event using Ajax and Codeigniter

I am using CodeIgniter v3.1.3 on WAMP.In one of my view (our_districts.php), i have a dropdownlist containing district names:
<select class="form-control" id="ddlDist" name="ddlDist" onchange="popDistrictData();">
<option value="0">--Select--</option>
<option value="3">District A</option>
<option value="4">District B</option>
<option value="5">District C</option>
<option value="6">District D</option>
</select>
<div id="districtData"></div>
<script type="text/javascript">
function popDistrictData(){
var dist_id = document.getElementById("ddlDist").value;
$.ajax({
type: "POST",
url: "<?=site_url()?>section/ajax_call_pop_district_data/"+dist_id,
dataType: "html",
success: function(html){
$("#districtData").html(html);
}
});
}
</script>
Section Controller:
class Section extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->output->set_header('Content-Type:text/html; charset=UTF-8');
$this->load->helper("url");
$this->load->model("District_model");
}
public function view()
{
$data['section_name']='Districts';
$this->load->view('templates/site_header',$data);
$data["district_data"] = $this->District_model->pop_districts_in_combobox();
$this->load->view('our_districts',$data);
$this->load->view('templates/site_footer',$data);
}
public function ajax_call_pop_district_data()
{
if ($this->input->post('distId') !="") {
$did = $_POST['distId'];
$dist_data = $this->District_model->pop_district_data($did);
//what should i write here???.........
}
}
}
As you can see that the above dropdownlist is getting populated by 'pop_districts_in_combobox()' method of 'District_model'.On its 'onchange' event,
i want to populate the div with id=districtData using Ajax as shown above.My problem is how to fill the div(id=districtData) .Please help with some code.Thanks in advance.
You're in an ajax call, so that ajax should return the code that will process the jQuery $.ajax function.
In your jQuery success function code you're doing a simple $("#districtData").html(html);
So in the controller function ajax_call_pop_district_data you should do a simple echo $dist_data which should have html code generated by the model function pop_district_data.

Javascripts don't work after calling changePage()

Javascript doesn't work after calling changePage() in my example. Everything is fine after first request page, but when I try to select other items, changePage() doesn't work. 'pageshow' event didn't help me. What's wrong with me?
My simple example:
#model TestMobileSearch.Models.ListModelView
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
$(document).delegate("#main", "pageinit", function () {
$("#filterCategory").bind('change', function () {
$.mobile.changePage(this.value);
});
});
</script>
Category Name: #Model.CurrentName
<select id="filterCategory" data-theme="c" data-corners="false">
#foreach (var item in Model.Names)
{
<option value="#Url.Action("List", "Cat", new {name = item})">#item</option>
}
</select>
I use jquery.mobile-1.3.1.js
Thanks
Why don't you delegate directly the #filtercategory change event?
$(document).delegate("#filterCategory", "change", function () {
$.mobile.changePage(this.value);
});
By the way, delegate is deprecated. If you use a newer jQuery, use on instead.

Resources