jQuery. Wait input values in modal Bootstrap - javascript

I got a script that show modal bootstrap and get input values to operate with him. But my problem is that script dont stop the input values inserted by user.
MODAL:
<!-- Modal -->
<div class="modal fade" id="imageModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12 col-sm-12 col-md-6 form-group">
<label for="f-type_id">Type image</label>
<select class="form-control">
<option value="">- Please select -</option>
#foreach($types as $type)
<option id="type_id" value="{{ $type->id
}}">
{{ $type->name }}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-12 col-md-6 form-group">
<label for="main">
<input type="checkbox" class="form-control"
id="main">
Main Image?
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn data-target='#imageModal'
data-toggle='modal'>Save
</button>
</div>
</div>
</div>
And Script:
var $listOfImages = $('#listOfImages');
$('#addImageButton').click(function() {
FileManagerFunctions.open('images', function(url, filePath) {
// Add image element
$('#imageModal').modal('show');
var $type = $('#type_id').val();
var $main = $('#main').val();
var $newImage = imageHtml(filePath, $type, $main);
$listOfImages.append($newImage);
});
});
imageHtml is a function that make an arrray with these values (#type_id & #main) but I need stop ejecution of script until user insert $type & $main values
May be is possible stop script until modal are closed? No idea...
If I use debug browser I can check that variable values are passing to function imageHtml before that user insert values
Thanks in advance!

If I am understanding your question correctly, you could just do any checks you need to $type and $main before you run your function.
e.g.
var $listOfImages = $('#listOfImages');
$('#addImageButton').click(function() {
FileManagerFunctions.open('images', function(url, filePath) {
// Add image element
$('#imageModal').modal('show');
var $type = $('#type_id').val();
var $main = $('#main').val();
var $newImage = imageHtml(filePath, $type, $main);
if ($type !== '' && $main !== '') {
$listOfImages.append($newImage);
} else {
alert('please enter a value for name and type')
}
});
});
EDITED:
This resolve problem in part.
I added id="addImageData" in button modal and now rest of script wait modal closing. But problem now is value input arent correct. This solution is bad and doesnt work correctly. But May be is a idea that I need...

Related

Issue hiding fields on multiple rendered form

I am trying to render a form for each person that I get based on a specific input from the database.
#forelse($driverNames as $driver)
<form id="inspection_report_form" enctype="multipart/form-data" action="/inspection-report/store" method="POST">
#csrf
I am trying to hide some fileds if no is selected from dropdown.
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<label>Equipment</label>
<div class="input-group mb-3">
<select class="custom-select" id="branded_equipment" name="branded_equipment" required>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>
<script>
let branded_equipment = document.getElementById('branded_equipment');
branded_equipment.addEventListener('change', function () {
if (branded_equipment.value === 'no') {
document.getElementById('branded_equipment_picture').required = false;
document.getElementById('branded_equipment_picture').disabled = true;
document.getElementById('branded_equipment_picture').style.display = 'none';
document.getElementById('branded_equipment_picture_label').style.display = 'none';
} else {
document.getElementById('branded_equipment_picture').required = true;
document.getElementById('branded_equipment_picture').disabled = false;
document.getElementById('branded_equipment_picture').style.display = 'block';
document.getElementById('branded_equipment_picture_label').style.display = 'block';
}
});
</script>
The problem that I am facing is that it works only for the first form in the list , if i am clicking on the next person form on the same dropdown id does nothing.
Same with the spinner
>! html
<div class="float-right">
{{--loader--}}
<button class="btn btn-primary" type="button" style="display: none" disabled id="spinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading ...
</button>
<button class="btn btn-success" id="report_submit_btn">Save</button>
</div>
>! javascript
let report_submit_btn = document.getElementById('report_submit_btn');
report_submit_btn.addEventListener('click', function () {
report_submit_btn.style.display = 'none';
document.getElementById('spinner').style.display = 'block';
});
I am assuming that because of the form is generated multiple times and the dropdown is having the same id for each iteration it does not know how to make the difference after the first form.
Much appreciated if anyone can help.
I have tryied using multiple selectors or techniques but nothing works. I am wondering if is achievable what I am trying to do or I should try something different.

Why does form submission not work after an installation of npm?

I created an app to analize Posts and Posters in a blog using Laravel 6. However the form submission to select a Post or a Poster doesn't work for some reasons.
I suppose the problems started after I deleted npm modules and I installed another time npm.
This is my code:
#extends('layouts.layout')
#section('content')
<form method="GET" id="poster_submit">
#csrf
<div class="form-group mt-5 col-sm-6 offset-sm-3">
<label for="select_poster" class="text-primary">Select a <b>Poster</b>:</label>
<div class="row">
<div class="col">
<select class="form-control" id="select_poster">
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->surname . " " . $user->firstname }}</option>
#endforeach
</select>
</div>
<div class="col">
<button type="submit" class="btn btn-primary btn-width">Go to the Poster!</button>
</div>
</div>
</div>
</form>
<form method="GET" id="post_submit">
#csrf
<div class="form-group col-sm-6 offset-sm-3 mt-5">
<label for="select_post" class="text-danger">Select a <b>Post</b>:</label>
<div class="row">
<div class="col">
<select class="form-control" id="select_post">
#foreach ($posts as $post)
<option value="{{ $post->id }}">{{ $post->id . " - " . $post->title }}</option>
#endforeach
</select>
</div>
<div class="col">
<button type="submit" class="btn btn-danger btn-width">Go to the Post!</button>
</div>
</div>
</div>
</form>
<script type="application/javascript">
$("#poster_submit").on("submit", function (e) {
e.preventDefault();
var poster_id = document.getElementById("select_poster");
var id = poster_id.options[poster_id.selectedIndex].value;
alert(id);
window.location = "profile/" + id;
});
$("#post_submit").on("submit", function (e) {
e.preventDefault();
var post_id = document.getElementById("select_post");
var id = post_id.options[post_id.selectedIndex].value;
alert(id);
window.location = "post/" + id;
});
</script>
#endsection
When I click a button nothing happens but I don't see any errors. I checked that JQuery works correctly.
When I click a button I should see an alert and then I should be redirected to another page but that doesn't happen because the form submission doesn't work.
Have you any idea?
You should make sure jQuery is loaded before running this code. Try wrapping this with additional code like this:
<script type="application/javascript">
$(function() {
$("#poster_submit").on("submit", function (e) {
e.preventDefault();
var poster_id = document.getElementById("select_poster");
var id = poster_id.options[poster_id.selectedIndex].value;
alert(id);
window.location = "profile/" + id;
});
$("#post_submit").on("submit", function (e) {
e.preventDefault();
var post_id = document.getElementById("select_post");
var id = post_id.options[post_id.selectedIndex].value;
alert(id);
window.location = "post/" + id;
});
});
</script>
Otherwise please include your JavaScript console log
Since you have put
e.preventDefault()
In your submit event, it will prevent the form to submit.
Basically what you can do is you can remove the e.preventDefault() and let the form submit to a method of your controller and from within the method redirect to new URL.

Modal pop up one time per user

In my website, I am using a simple modal popup with some input controls ( name, email, button).
The purpose of modal popup is:
After filling all mandatory fields, if user press "submit" button they will get one .pdf file.
I launch the modal upon onload.
Here, I am trying to do:
Open the modal popup only once for a user, or
Don't want to show the modal popup to users who previously filled out the form already
Here is the code of my modal popup:
<script type="text/javascript">
$(document).ready(function () {
$("#eBookModal").modal('show');
});
</script>
<div class="modal fade" id="eBookModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="row">
<h4 class="modal-title text-center" style="color:#FFFFFF;">Download eBook</h4>
</div>
</div>
<div class="modal-body">
<form role="form" id="eBookform" class="contact-form"
action="file.pdf">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="FName" autocomplete="off" id="eBook_FName" placeholder="First Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="LName" autocomplete="off" id="eBook_LName" placeholder="Last Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="email" class="form-control form-text" name="email" autocomplete="off" id="eBook_email" placeholder="E-mail" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center" id="eBook_download">
<button type="submit" class="btn main-btn" style="color:#fff !important;">Download Now</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
You have to keep record of the modal displays. To store that info, you can either use a cookie or the localStorage. Based on the stored value, you can decide whether to show the modal or not.
The sample below uses the localStorage as an example:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
Available as a Codepen too.
If you would like to hide the modal just from those who already submitted the form, you should set the flag upon form submit, like so:
$('#eBookform').on('submit', function (event) {
// event.preventDefault();// depending on your use case
localStorage.setItem(key, true);
})
Note: to reset the stored value, just call localStorage.removeItem('hadModal').
If you just to show the modal one time for first time visit and previous code didn't work try this !
$(window).load(function(){
var Modal = document.getElementById('myModal');
var key = 'hadModal',
hadModal = localStorage.getItem(key);
if (!hadModal) {
Modal.style.display = "block";
localStorage.setItem(key, true);
}
});
if (document.cookie.indexOf("ModalShown=true")<0) {
jQuery(document).ready(function() {
setTimeout(function(){
$("#homepageModal").addClass("modal-show")
}, 1000);
});
var date = new Date(),
expires = 'expires=';
date.setDate(date.getDate() + 1);
expires += date.toGMTString();
document.cookie = 'ModalShown=true ;' + expires + '; path=/';
}
How do you get this script to work in Bootstrap 5 without using jQuery?
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});

jQuery result beign overwritten by the info sent from the GET Method [duplicate]

This question already has answers here:
jQuery: Conflict with removeData() executing at inadequate times
(3 answers)
Closed 5 years ago.
I have a modal window used to update or add a new object Store.
This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.
Button that calls the modal:
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
Html of the modal:
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
GET Method:
public IActionResult Create(int? id)
{
List<Department> DepartmentList = new List<Department>();
DepartmentList = (from department in _context.Departments
select department).ToList();
DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
ViewBag.ListofDepartment = DepartmentList;
StoreIndexData edit = new StoreIndexData();
List<District> ListofDistrict = new List<District>();
ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
ViewBag.ListofDistrict = ListofDistrict;
return PartialView("~/Views/Shared/Stores/_Create.cshtml");
}
The problem:
I have the following jQuery which asigns a value to DistrictID once the modal opens:
<script type="text/javascript">
var wasclicked = 0;
var $this = this;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
};
$('#modal-action-store').on('hidden.bs.modal', function () {
//global.wasclicked = 0;
wasclicked = 0;
$(this).removeData('bs.modal');
});
$('#modal-action-store').on('shown.bs.modal', function (e) {
console.log($('#DistrictID').length);
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
};
});
});
</script>
The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :
ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
And this line is lost:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
What I suspect is that the information coming from the Controller overwrites any result from jQuery over the in the modal.
After debugging I have identified three diferent moments:
Moment 1: First time we open the modal
The modal hasn't opened yet and the jQuery executes
For this reason it does not identify DistrictID
The result from the GET Action fills the modal's inputs.
Moment 2 - Part 1: Second time we open the modal
This time the modal opens before the jQuery is executed
The DistrictID has the value from the GET Method before we assign the value from jQuery
Moment 2 - Part 2: When the value from jQuery is assigned
The value from jQuery is assigned to DistrictID
This value will be overwritten by the result of the GET Action
Question:
Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?
Try to replace your code:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
by
var items = "<option value='0'>-- Seleccione Distrito --</option>";
var currentItems = $('#DistrictID').html();
$('#DistrictID').html(items + currentItems)
Hope this helps you :)
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
}
});
</script>
PS: Default option can be also be used. refer the below code.
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
<option value='0'>-- Seleccione Distrito --</option>
</select>
</div>
</div>

Firebase Chat change reference with javascript

I am trying out how to incorporate firebase with angular in such a way that the user is able to change the "Channel" of the chat via selecting from a dropdownlist.
This is the code that I have at the moment:
Note: The channel attribute is defined in another portion of code, and the entire page is loaded only once.
app.controller('mychat', function($scope, $firebaseArray) {
var d = new Date();
var today = d.getDate()+d.getMonth()+d.getYear();
var txt = document.getElementById('txtFBMsgs'); //store id of textbox
//Query
var ref = firebase.database().ref().child(channel)
$scope.fbmessages = $firebaseArray(ref);
$scope.send = function() {
if (txt.value != ""){ //check if textbox contains any message
$scope.fbmessages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
txt.value = ""; //reset value of textbox
}
}
})
and here is my html portion:
<div class="card mb-1 col-md-3" ng-controller="mychat" id="myDiv">
<div class="card-body" style="overflow-x: hidden; overflow-y:scroll; min-height:60vh; max-height:64vh;">
<div>
<p ng-repeat="m in fbmessages"> {{m.date | date:'short'}} - {{m.sender}}: <br> {{m.message}}</p>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-9">
<input type="text" id = "txtFBMsgs" class="form-control" placeholder="Message here..." ng-model="messageText" onkeydown = "if (event.keyCode == 13) document.getElementById('sendBtn').click()">
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
basically, it is a div that displays the chat messages, and an input box which is able to send the message to firebase.
Can I change the 'Channel' dynamically via javascript, such as on an onchange in a DDL?

Categories

Resources