Why does my CSS code renders incorrectly on iOS/MacOS? - ios

We developed a web app on Vue 3 and it displays perfectly on every browser except on iOS and Mac OS devices.
This is worse if you're using Safari, however some issues occur even on Chrome for Mac.
This problem causes forms to always be shown blank, without displaying a placeholder or user input. It also makes several other elements to misalign.
We even tried making a new form and removing all stylesheets, but the problem persists.
Here is the code for one of the forms:
<template>
<div>
<form class="contactus" #submit.prevent="saveMessage">
<div class="row">
<h1 class="titleFormAbout">
{{ $t("contactus.componentForm.text1") }}
</h1>
</div>
<p style="margin-bottom: 30px;">{{ $t("contactus.componentForm.text9") }}</p>
<input type="text" class="form-control formContact" :placeholder="$t('contactus.componentForm.text2')" id="name" required />
<input type="email" class="form-control formContact" :placeholder="$t('contactus.componentForm.text3')" id="email" required />
<vue-tel-input
v-model="phone"
id="phone"
class="formControl formContact"
></vue-tel-input>
<br />
<textarea
class="form-control formContact"
name=""
id="message"
rows="10"
:placeholder="$t('contactus.componentForm.text5')"
required
></textarea>
<br />
<vue-recaptcha
style="margin-bottom: 14px"
#validate="validated"
/>
<div class="row">
<div class="col-6">
<input
class="form-control "
type="Submit"
id="submitButton"
:value="$t('contactus.componentForm.text6')"
disabled
/>
</div>
<div class="col-6">
<button class="form-control clear" #click="clearForm" >
{{ $t("contactus.buttonClear") }}
</button>
</div>
</div>
<br />
<div class="alert" id="Response" role="alert"></div>
</form>
</div>
</template>
<script>
import axios from "axios";
import VueRecaptcha from "../forms/vue-recaptcha.vue";
const hostName = location.port =="" ?location.protocol + "//" + location.host:'http://'+location.hostname+':3000';
export default {
components: {
VueRecaptcha,
},
data() {
return {
config: {
headers: {
//'Content-Type': 'application/x-www-form-urlencoded'
"Content-Type": "multipart/form-data",
},
},
};
},
methods: {
validated(){
const htmlElement=document.getElementById('submitButton');
htmlElement.classList.add('submit');
htmlElement.disabled=false;
},
clearForm() {
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementsByName("telephone")[0].value = "";
document.getElementById("message").value= "";
},
saveMessage() {
//alert(document.getElementsByClassName("highlighted")[0].getElementsByTagName('span')[0].innerHTML)
const responseBox = document.getElementById("Response");
const params = new FormData();
const countryPhone = document.getElementsByClassName("highlighted");
var countryPhoneid = "+52";
if (countryPhone.length > 0) {
countryPhoneid =
countryPhone[0].getElementsByTagName("span")[0].innerHTML;
}
params.append("name", document.getElementById("name").value);
params.append("email", document.getElementById("email").value);
params.append("phone",countryPhoneid + " " + document.getElementsByName("telephone")[0].value);
params.append("message", document.getElementById("message").value);
axios
.post(hostName + "/api/contact", params, this.config)
.then((response) => {
responseBox.innerHTML = this.$t("contactus.componentForm.text7");
responseBox.classList.add("alert-success");
setTimeout(() => {
responseBox.classList.remove("alert-success");
}, 5000);
console.log(response);
})
.catch((err) => {
responseBox.innerHTML = this.$t("contactus.componentForm.text8");
responseBox.classList.add("alert-danger");
setTimeout(() => {
responseBox.classList.remove("alert-danger");
}, 5000);
console.log(err);
});
responseBox.hidden = false;
setTimeout(() => {
responseBox.hidden = true;
}, 5000);
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementsByName("telephone")[0].value = "";
document.getElementById("message").value = "";
},
},
mounted() {
document.getElementsByName("telephone")[0].placeholder=this.$t('contactus.componentForm.text10');
const listcountry = document.getElementsByClassName("vti__dropdown-list");
listcountry[0].getElementsByTagName("li")[137].classList.add("highlighted");
document.getElementsByName("telephone")[0].required = true;
document
.getElementsByName("telephone")[0]
.addEventListener("input", (textin) => {
const telephone = document.getElementsByName("telephone")[0];
//console.log(parseInt(textin.data));
//console.log(Number.isInteger(textin.data));<
if (Number.isInteger(parseInt(textin.data))) {
// console.log(telephone.value);
} else {
telephone.value = telephone.value.slice(
0,
telephone.value.length - 1
);
}
});
},
};
</script>
<style>
.contactus .submit {
background: #008b9e;
color: white;
font-weight: bold;
}
.contactus .formContact{
border: 2px solid #BAD1FF;
margin-top: 2vh;
margin-bottom: 2vh;
}
.contactus .clear {
background: rgba(0, 0, 0, 0.25);
font-weight: bold;
}
.contactus .titleFormAbout {
margin-top: 20px;
margin-bottom: 20px;
text-align: left;
color: #00a8c6;
font-weight: bolder;
margin-left: 12px;
text-transform: none;
}
form.contactus {
padding-left: 5vw;
padding-right: 5vw;
}
.contactus form li {
color: black;
}
.contactus .alet {
text-align: center;
}
.contactus .contactus p{
text-align: justify;
}
</style>
Here you can see the type of behaviour we're getting:
On iOS/MacOS:
The same elements on Windows/Android devices:
Can anyone please tell me if this is a common issue and if there's a solution? We have been stuck with this problem for two weeks and we're losing our minds.
Thanks.

Related

asp.net core page not found

I have error "Page not found" on my website.
This is what i have came up with.
Error occurred to clients few times without me knowing exact moment
When i tested it it ALWAYS happens when i restart my website asp.net server but under some circumstances which i will describe later
It happens in some controllers but in some not
It happens only until i open some controller that will load website, then all other works too.
It happens only on published website and not in my local environment.
So first line is clear and doesn't need explanation.
Second line:
What i have tested to get this error is i shut down my server and then start it again. After it i try going to mywebsite.com/User and error comes.
Third line:
It only happens in controllers /User and /Kalkulator but not in / or /Proizvodi
Forth line:
When i open controller /User and refresh it multiple times it doesn't load but when i go to / and then to /User it loads.
Here are my controllers with their views. I will only provide /User and /Kalkulator since there is easiest to see what happens.
public class UserController : Controller
{
public IActionResult Index()
{
//Debug log are control lines that write to my txt file but they are never reached on first time going to this controller, but when i do fourth step they do reach.
Debug.Log(null, "User/Index pocetak", Debug.Type.CasualChange, Request);
try
{
Debug.Log(null, "User/Index Checking isLogged", Debug.Type.CasualChange, Request);
if (Networking.IsLogged(Request))
{
Debug.Log(null, "User/Index Checking isAdmin", Debug.Type.CasualChange, Request);
if (Networking.IsAdmin(Request))
{
Debug.Log(null, "User/Index Return redirect admin", Debug.Type.CasualChange, Request);
return Redirect("/Admin?select=POR");
}
else
{
Debug.Log(null, "User/Index Return redirect /Proizvodi", Debug.Type.CasualChange, Request);
return Redirect("/Proizvodi");
}
}
Debug.Log(null, "User/Index Creting new user class", Debug.Type.CasualChange, Request);
AR.TDShop.User u = new AR.TDShop.User();
Debug.Log(null, "User/Index Return view with user class", Debug.Type.CasualChange, Request);
return View(u);
}
catch (Exception ex)
{
Debug.Log(null, "User/Index catch error", Debug.Type.CasualChange, Request);
return View("Error", ex.ToString());
}
}
User View
#model AR.TDShop.User
#{
ViewData["Title"] = "Profi kutak";
}
<style>
#Login {
margin: auto;
position: relative;
width: 400px;
text-align: center;
margin-top: 100px;
border-radius: 10px;
border: 1px solid red;
}
#Login input {
margin-top: 10px;
text-align: center;
height: 40px;
font-size: 30px;
width: 60%;
}
#Login button {
margin-top: 20px;
margin-bottom: 20px;
width: 200px;
height: 40px;
font-size: 18px;
border: none;
background-color: #ff0000;
border-radius: 0px 0px 20px 20px;
color: white;
font-weight: bolder;
}
#Login button:hover {
background-color: #ff4d4d;
}
#PostaniClan button:hover {
background-color: lawngreen !important;
color: black !important;
}
</style>
#using (Html.BeginForm("Login", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="Login">
<p style="padding-top: 10px; padding-bottom: 10px; border-radius: 10px 10px 0 0; color: white; background-color: red; font-weight: bolder; font-size: x-large">Logovanje</p>
#Html.TextBoxFor(x => x.Name, new { #placeholder = "username" })
<br />
#Html.TextBoxFor(x => x.PW, new { #placeholder = "password", #type = "password" })
<br />
<button type="submit">Potvrdi</button>
</div>
}
<div style="text-align: center; margin-top: 30px; margin-bottom: 30px" id="PostaniClan">
<button onclick="window.location.href='/Majstori/Registracija'" style="background-color: green; color: white; border-radius: 20px; padding: 10px 20px 10px 20px;">Postani član!</button>
</div>
}
As you can see in user controller/view there are few other commands that are not shown here but i think you do not need them and you will get it when you take a look at /Kalkulator controller which also doesn't works and here it is:
public class KalkulatorController : Controller
{
public IActionResult Index()
{
return View();
}
}
and here is the view:
#{
ViewData["Title"] = "Kalkulator";
}
<div class="main-wrapper">
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Plafon</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za izradu spustenog plafona u gips karton sistemu.</p>
Izracunaj!
</div>
</div>
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Zid (oblaganje)</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za oblaganje postojeceg zida.</p>
Izracunaj!
</div>
</div>
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Zid (pregradjivanje)</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za izradu novog pregradnog zida.</p>
Izracunaj!
</div>
</div>
</div>
As you can see it is pure HTML and it doesn't work....
Here is my /Proizvodi controller which works (it has a lot of commands so i will display only index and view)
public IActionResult Index(int? GrupaID, int? PodgrupaID, int? V, string Pretraga)
{
ProizvodiModel pm = new ProizvodiModel(GrupaID, PodgrupaID, V, Request);
pm.Tag = Pretraga;
return View(pm);
}
VIEW:
#model ProizvodiModel
#{
ViewData["Title"] = "Proizvodi";
List<Tuple<int, double>> CeneZaKorisnika = new List<Tuple<int, double>>();
if (Networking.IsLogged(Context.Request))
{
CeneZaKorisnika = AR.TDShop.User.GetVPCene(Model.User.UserID);
CeneZaKorisnika.Sort((x, y) => x.Item1.CompareTo(y.Item1));
}
if (!Model.Majstor)
{
<style>
.proizvod {
margin-bottom: 5px !important;
}
</style>
}
else
{
<style>
.proizvod {
margin-bottom: 103px !important;
}
</style>
}
}
<link rel="stylesheet" type="text/css" href="~/css/ProizvodiIndex.css" />
<div class="main-wrapper">
<div id="left" class="col-sm-3" style=" color: white">
<div style="width: 100%; margin-top: 40px; margin-bottom: 40px; text-align: center">
<img src="~/images/Logo_Long.png" style="width: 90%;" />
</div>
#if (Model.Majstor)
{
Model.User.UcitajPorudzbine(Context.Request);
if (Model.User.Porudzbine.Count > 0)
{
<div style="background-color: red; margin-top: 10px; padding-top: 10px; padding-bottom: 10px">
<h3 style="text-align: center; margin: 0;">Skorašnje porudžbine</h3>
#{
int n = 5;
<table id="PorudzbineTable" style="width: 100%;margin-top: 10px; background-color: #ffbbbb; color: black">
#foreach (AR.TDShop.Porudzbina p in Model.User.Porudzbine)
{
<tr onclick="window.location.href='/Porudzbina?ID=' + #p.PorudzbinaID">
<td style="padding-left: 10px">#p.BrDokKom</td>
#switch (p.Status)
{
case AR.TDShop.Porudzbina.PorudzbinaStatus.NaObradi:
<td>Na obradi!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.CekaUplatu:
<td>Čeka uplatu!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.ZaPreuzimanje:
<td>Za preuzimanje!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.Preuzeto:
<td>Realizovano!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.Stornirana:
<td>Stornirano!</td>
break;
}
</tr>
n--;
if (n <= 0)
{
break;
}
}
</table>
<button id="SvePorudzbine" onclick="window.location.href='/User/Porudzbine'" style="text-align: center; margin-top: 10px; background-color: white; color: black">Sve porudzbine</button>
}
</div>
}
<div id="ObjasnjenjeCene">
<p>Cena bez PDV-a je iskazana crvenom bojom!</p>
</div>
}
<div style="padding: 15px; background-color: #5a5cd4; margin-bottom: 40px">
<button class="#if (#Model.ActivateGrupa == null && Model.ActivatePodgrupa == null) { #Html.Raw("activate") }" onclick="GoTo('/Proizvodi')">Svi proizvodi</button>
#foreach (GrupaModel g in Model.Grupe)
{
<button class="#if (Model.ActivateGrupa != null && Model.ActivateGrupa == g.GrupaID)
{
#Html.Raw("activate")
} else if (#Model.ActivatePodgrupa != null)
{
if(PodgrupaModel.GetParent((int)Model.ActivatePodgrupa) == g.GrupaID) { #Html.Raw("activate") }
}"
onclick="GoTo('/Proizvodi?GrupaID=#g.GrupaID')">
#g.Naziv
</button>
}
</div>
<div id="PredloziProizvod" style="border-top: black 2px; color: black;">
<button id="predloziButton" style="width: 100%; text-align: center">Predloži proizvod</button>
<input hidden type="text" placeholder="Naziv proizvoda" />
<input hidden type="text" placeholder="Kataloski broj" />
<input hidden type="text" placeholder="Opis primene" />
<button hidden id="PosaljiPredlogProizvoda">Posalji</button>
</div>
</div>
<div id="right" class="col-sm-9">
<div id="PretragaProizvoda">
<input type="text" placeholder="Pretraga..." value="#Model.Tag" />
<button id="tw" style="float: right" onclick="ToggleView(this)" value="0"><img src="~/images/View2.png" style="width: 25px" /></button>
</div>
<br />
#if (Model.PodGrupe.Count > 0)
{
string cls = "";
if (Model.ActivatePodgrupa == null)
{
cls = "aktivnaPodgrupa";
}
<div id="PodGrupe">
<button class="PodGrupa #cls" onclick="GoTo('/Proizvodi?GrupaID=#PodgrupaModel.GetParent((int)Model.PodGrupe[0].PodgrupaID))'">
<p>Svi proizvodi grupe</p>
</button>
#foreach (PodgrupaModel pgm in Model.PodGrupe)
{
cls = "";
if (pgm.PodgrupaID == Model.ActivatePodgrupa)
{
cls = "aktivnaPodgrupa";
}
<button class="PodGrupa #cls" onclick="GoTo('/Proizvodi?PodgrupaID=#pgm.PodgrupaID')">
<p>#pgm.Naziv</p>
</button>
}
</div>
<hr style="border-bottom: 2px solid black" />
}
#foreach (ProizvodModel p in Model.Proizvodi)
{
if (p.Aktivan)
{
string proizvodStil;
string buttonStil;
if (p.Klasifikacija == 0)
{
proizvodStil = "color: dimgray;";
buttonStil = "background: linear-gradient(to bottom, white, dimgray 20%, dimgray 80%, white 100%);";
}
else if (p.Klasifikacija == 2)
{
proizvodStil = "color: darkorange;";
buttonStil = "background: linear-gradient(to bottom, white, darkorange 20%, darkorange 80%, white 100%);";
}
else
{
proizvodStil = "color: darkgreen;";
buttonStil = "background: linear-gradient(to bottom, white, darkgreen 20%, darkgreen 80%, white 100%);";
}
<div class="proizvod ppppp #if (Model.Majstor) { #Html.Raw("korpa"); } normal"
#Html.Raw("onclick = \"GoToP('" + #p.ROBAID + "')\"") ;
style="#proizvodStil">
<p class="katBr">#p.KatBr</p>
<img src="#p.Slika" />
<p class="nazivProizvoda">#p.Naziv</p>
#if (Model.Majstor)
{
try
{
int NivoZaKorisnika = Model.User.Cenovnik_grupa.Where(x => x.Item1 == p.Cenovnik_GrupaID).Select(t => t.Item2).FirstOrDefault();
double VPCena = CeneZaKorisnika.Where(x => x.Item1 == p.ROBAID).FirstOrDefault().Item2;
double MPCena = VPCena + (VPCena * p.PDV / 100);
if (MPCena > 0)
{
<p class="vpcena">#VPCena.ToString("#,###.00") / #p.JM</p>
<p class="mpcena">#MPCena.ToString("#,###.00") / #p.JM</p>
if (Model.User.Vrsta == UserModel.Tip.Majstor)
{
<button style="#buttonStil" onclick="GoToP(#p.ROBAID); event.stopPropagation();"> KUPI!</button>
}
}
if (Model.User.Vrsta == UserModel.Tip.Administrator)
{
<button style="#buttonStil" onclick="Edit(#p.ROBAID); event.stopPropagation();">Detalji!</button>
}
}
catch (Exception ex)
{
#:alert("#ex.ToString()");
}
}
</div>
}
}
</div>
</div>
<div id="AlertPopUp">
</div>
<script src="~/js/AlertBox.js"></script>
<script>
var alb = new AlertBox($("#AlertPopUp"));
var currRID = -1;
var overwrite = false;
function GoTo(link) {
if ($("#tw").val() == 1) {
if (link.indexOf('?') > -1) {
window.location.href = link + "&V=1";
}
else {
window.location.href = link + "?V=1";
}
}
else {
window.location.href = link;
}
}
function GoToP(link) {
if ($("#tw").val() == 1) {
if (link.indexOf('?') > -1) {
window.location.href = link + "&V=1";
}
else {
window.location.href = link + "?V=1";
}
}
else {
window.location.href = "/Proizvod?ID=" + link;
}
}
function Edit(id) {
GoTo("/Proizvodi/Edit?ID=" + id);
}
function ToggleView(element) {
var curr = $(element).val();
if (curr == 1) {
$(element).val(0);
$(element).children("img").attr("src", "/images/View2.png");
$(".ppppp").removeClass("proizvod1");
$(".ppppp").addClass("block");
$(".ppppp").addClass("proizvod");
$(".korpa button").html("Dodaj u korpu!");
}
else {
$(element).val(1);
$(element).children("img").attr("src", "/images/View1.png");
$(".ppppp").removeClass("proizvod");
$(".ppppp").removeClass("block");
$(".ppppp").addClass("proizvod1");
$(".korpa button").html("<img src='/Images/cart.png' style='height: 50px;width: 50px;border-radius: 10px;padding: 5px;padding-right: 8px;background-color: #2196F3;' />");
}
}
#{
if(Model.View == 1)
{
#:StartOtherView();
}
}
function StartOtherView() {
$("#tw").val(1);
$("#tw").children("img").attr("src", "/images/View1.png");
$(".ppppp").removeClass("proizvod");
$(".ppppp").removeClass("block");
$(".ppppp").addClass("proizvod1");
$(".korpa button").html("<img src='/Images/cart.png' style='height: 50px;width: 50px;border-radius: 10px;padding: 5px;padding-right: 8px;background-color: #2196F3;' />");
}
$(function () {
var PredloziProizvodBlock = false;
$("#predloziButton").click(function () {
$(this).parent().children("input").each(function () {
if (PredloziProizvodBlock == true) {
$(this).hide();
}
else {
$(this).show();
}
});
if (PredloziProizvodBlock == true) {
$("#PosaljiPredlogProizvoda").hide();
}
else {
$("#PosaljiPredlogProizvoda").show();
}
PredloziProizvodBlock = !PredloziProizvodBlock;
})
$("#PosaljiPredlogProizvoda").click(function () {
$.ajax({
type: "GET",
url: "/Proizvodi/PosaljiPredlogProizvoda",
contentType: "application.json; charset-utf-8",
dataType: "json",
async: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
})
$("#PretragaProizvoda input").keyup(function () {
var input = $(this).val().toUpperCase();
$(".proizvod").each(function () {
if ($(this).html().toUpperCase().indexOf(input) >= 0 || input.length == 0) {
$(this).show();
}
else {
$(this).hide();
}
});
});
});
</script>
All views use same layout.
Routing option:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I think your problem with Redirect in you UserController, could your try replace it on RedirectToAction(); It's must be help you.
I found out mistake and it was so easy.
I thought i was checking all my code which is ran when entering some page but i forgot one big part and it is constructor:
private readonly IHostingEnvironment hostingEnvironment;
public ProizvodiController(IHostingEnvironment he)
{
hostingEnvironment = he;
Program.AbsolutePath = hostingEnvironment.WebRootPath;
Debug.FilePath = Path.Combine(Program.AbsolutePath, "Log");
}
public IActionResult Index(int? GrupaID, int? PodgrupaID, int? V, string Pretraga)
{
ProizvodiModel pm = new ProizvodiModel(GrupaID, PodgrupaID, V, Request);
pm.Tag = Pretraga;
return View(pm);
}
I forgot that constructor is accessed each time when you access any page from controller and it sets my AbsolutePath variable which i use later.
When i restart my server he lose all in memory data (which is static variable AbsolutePath) and it is only set when ANY user enter website but since i call it only in 2 controllers, other controllers were not working.
Solution was to add same code to all controllers constructors.

Add a button to Select2 Dropdown list

I am using the lastest version of Select2. Want to add an Insert New button at the end of the dropdown list. I tried these two solutions I found online
Solution 1:
$(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
Solution 2
$("#itemId0").select2("container").find("div.select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
With Solution 1 nothing happens. With solution 2 I get the error message in the select 2 js file
0x800a138f - JavaScript runtime error: Unable to get property 'apply'
of undefined or null reference
Can anyone please help?
Here is my HTML
<select id='itemId0' name='product[0][name]' class='form-control col-lg-5 itemSearch' >
<option></option>
</select>
AND the full select2 javascritp
function productFormatResult(product) {
if (product.loading) product.text;
var html = "<table><tr>";
html += "<td>";
html += product.text;
html += "</td></tr></table>";
return html;
}
// alert(html);
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='" + product.id + "'/>";
return selected + product.text;
}
//$("#itemId0").select2();
$("#itemId0").select2({
ajax: {
url: "#Url.Action("GetProducts", "Inventories")",
dataType: 'json',
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, params) {
return { results: data };
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: productFormatResult,
templateSelection: productFormatSelection,
dropdownClass: 'bigdrop'
});
// $(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
$("#itemId0").select2("container").find("div.select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
check it
$('#select2').select2({
placeholder: 'This is my placeholder',
language: {
noResults: function() {
return `<button style="width: 100%" type="button"
class="btn btn-primary"
onClick='task()'>+ Add New Item</button>
</li>`;
}
},
escapeMarkup: function (markup) {
return markup;
}
});
Update: (Explanation)
If you need to add button in select2 if no result found you just need to returnHTML Button code from noResults function and Add escapeMarkup function to render custom templates.
language: {
noResults: function() {
return `<button style="width: 100%" type="button"
class="btn btn-primary"
onClick='task()'>+ Add New Item</button>
</li>`;
}
},
escapeMarkup: function (markup) {
return markup;
}
Try below example to see how it looks.
https://jsfiddle.net/Hamza_T/yshjqw85/32/
Here is an example in codepen
html is below
<select id="CustomSelect" multiple="multiple">
<option value="volvo">BMW</option>
<option value="saab">Jaquar</option>
<option value="mercedes">RR</option>
<option value="audi">Audi</option>
</select>
CSS is below
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
Script is below
$("#CustomSelect").select2({
width: '100%',
allowClear: true,
closeOnSelect: false
}).on('select2:open', function () {
let a = $(this).data('select2');
if (!$('.select2-link').length) {
a.$results.parents('.select2-results')
.append('<div class="select2-link2 select2-close"><button>Close</button></div>')
.on('click', function (b) {
});
}
});
I think this can be done with Select2's Adapters and Decorators (https://select2.org/advanced/default-adapters). However, personally I find this approach really heavy and to be honest I don't understand the documentation regarding this area.
What I personally do, is binding on the select2:open-event and appending a add-new-button container.
Here is an example:
// create new container
$('#select2').select2CreateNew("Create new");
// generic function
$.fn.select2CreateNew = function( text ) {
// bind to "open"-event
this.on( 'select2:open', function( e ) {
let name = $( this ).attr( 'name' );
let html = '<div class="s-add-new-container">' + text + '</div>';
let $resultContainer = $( '[aria-controls="select2-' + name + '-results"]' )
.closest( '.select2-dropdown' ).find( '.select2-results' );
// avoid duplicates ~ append "create new" to result bottom
if ( $resultContainer.find( '.s-add-new-container' ).length === 0 ) $resultContainer.append( html );
} );
}
Customize the code or add some click-event handler for whenever the user clicks on the container.
For styling I'm using this CSS:
.s-add-new-container {
padding: 7px;
background: #f1f1f1;
border-top: 1px solid #c7c7c7;
}
.select2-dropdown.select2-dropdown--below {
border-radius: 0px;
box-shadow: 0px 5px 10px #6b6b6b59;
}
.s-add-new-container:hover {
background: #3db470;
color: white;
cursor: pointer;
}

Floating Label not working on jquery mobile 1.4.4

I am trying to make a floating label float when you click the input. I am using CSS and jquery(This is in a jquery mobile 1.4.4 platform). My code only seems to work on an input with a data-role of "none," and it won't work on a normal input. How can I make this work on a normal input?
This is my CSS:
.inputAnimation {
display: inline-block;
position: relative;
margin: 0 0px 0 0;
}
.inputAnimation label {
position: absolute;
top: 5px;
left: 15px;
font-size: 12px;
color: #aaa;
transition: .1s all linear;
cursor: text;
}
.inputAnimation.active label {
top: -15px;
}
This is my HTML:
<div data-role="page" id="signUpPage">
<div data-role="main" class="ui-content">
<form>
<div class="inputAnimation">
<label for="username">Name</label>
<input id="username" name="username" type="text" />
</div>
<div class="inputAnimation">
<label for="email">Email</label>
<input data-role="none" id="email" name="email" type="text" />
</div>
</form>
</div>
And this is my jquery
$(document).ready(function () {
$('input').each(function () {
$(this).on('focus', function () {
$(this).parent('.inputAnimation').addClass('active');
});
$(this).on('blur', function () {
if ($(this).val().length == 0) {
$(this).parent('.inputAnimation').removeClass('active');
}
});
if ($(this).val() != '') $(this).parent('.inputAnimation').addClass('active');
});
});
Here is the demo
Link to the jsfiddle
Thanks!
When jQM enhances the input it adds a DIV such that .inputAnimation is now a grandparent of the input instead of parent. The simplest change is to use the .parents() instead of .parent() method:
$('input').each(function () {
$(this).on('focus', function () {
$(this).parents('.inputAnimation').addClass('active');
});
$(this).on('blur', function () {
if ($(this).val().length == 0) {
$(this).parents('.inputAnimation').removeClass('active');
}
});
if ($(this).val() != '') $(this).parents('.inputAnimation').addClass('active');
});
Updated FIDDLE

Razor code error

I have the following code :
#{
var db = Database.Open("WebPageMovies") ;
var selectCommand = "SELECT * FROM Movies";
var searchGenre = "";
var searchTitle = "";
var selectedData = "";
// search by Genre
if(!Request.QueryString["searchGenre"].IsEmpty() ) {
selectCommand = "SELECT * FROM Movies WHERE Genre = #0";
searchGenre = Request.QueryString["searchGenre"];
}
// searching by title ( but any word or words that match a title will work).
if(!Request.QueryString["searchTitle"].IsEmpty()){
selectCommand += " AND Title LIKE #1";
searchTitle = "%"+ Request.QueryString["searchTitle"] + "%";
}
// if both textboxes are empty, then the following is dispayed
if(searchGenre != null)
{
selectedData = db.Query(selectCommand, searchGenre,searchTitle);
}
else
{
selectedData = db.Query(selectCommand,searchTitle);
}
var grid = new WebGrid(source: selectedData, defaultSort: "Genre", rowsPerPage:3);
}
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.grid { margin: 4px; border-collapse: collapse; width: 600px; }
.grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; }
.head { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
.alt { background-color: #E8E8E8; color: #000; }
</style>
<meta charset="utf-8" />
<title>Movies</title>
</head>
</head>
<body>
<h1>Movies</h1>
<form method="get">
<div>
<label for="searchGenre">Genre to look for:</label>
<!-- in order for the textbox to rememebr what search value was entered, we need to provide a value attribute with that search value in our HTML-->
<input type="text" value="#Request.QueryString["searchGenre"]" name="searchGenre" value="" />
#*<input type="Submit" value="Search Genre" /><br/>*#
(Leave blank to list all movies.)<br/>
</div>
<div>
<label for="SearchTitle">Movie title contains the following:</label>
<input type="text" name="searchTitle" value="#Request.QueryString["searchTitle"]" />
<input type="Submit" value="Search Title" /><br/>
</div>
</form>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Title"),
grid.Column("Genre"),
grid.Column("Year")
)
)
</div>
</body>
</html>
Don't worry about the length of it, just focus on the razor code. In brief, I have two textboxes and one button. I would like to display a table when a user puts in a value in either the "Title" or the "Genre" or both the search boxes. However, I am getting the following error:
You error is related to the type of this variable that happens to be string:
var selectedData = "";
See that you're trying to assign the query result to it and db.Query returns an IEnumerable<dynamic>.
selectedData = db.Query(selectCommand, searchGenre,searchTitle);
Change that variable to:
IEnumerable<dynamic> selectedData;

Ajax ModalPopupExtender with an edit form in ASP.NET MVC

I have an events calendar and on each event in the calendar there is an edit link which open up ajax ModalPopupExtender for editing the event information. The issue that I am facing right now is that the edit has to be in a form so it can update the information on the server..
How do I deal with this? And what would be the best way of doing this ?
You can use jQuery to accomplish the same functionality. I had to do this recently for a project because I didn't like the way the ModalPopupExtender was handling it. Unfortunately though I didn't build the drag click-and-drag functionality.
Here's the code for the ASP.NET and XHTML:
Somewhere on the page, you put trigger button:
<input type="button" value="Trigger Action" class="popup-trigger-delete" />
Panel Code:
<div class="popup-wrapper popup-wrapper-delete">
<div class="popup-top"></div>
<div class="popup-middle">
<div class="content">Are you sure you want to delete this from your project?</div>
<div class="controls">
<asp:Button ID="btnDelete_Yes" runat="server" CssClass="left" OnClick="btnDelete_Yes_OnClick" />
<input type="button" value="Cancel" class="right popup-background-delete-cancel" />
</div>
</div>
<div class="popup-bottom"></div>
</div>
<div class="popup-background popup-background-delete-track"></div>
Javascript / jQuery
var fadeInTime = 400;
var popupStatus = 0;
function loadPopup(wrapper){
//loads popup only if it is disabled
if(popupStatus==0){
$(wrapper).fadeIn(fadeInTime);
popupStatus = 1;
}
}
function disablePopup(wrapper, background){
if(popupStatus==1){
$(background).fadeOut(fadeInTime);
$(wrapper).fadeOut(fadeInTime);
popupStatus = 0;
}
}
function centerPopup(wrapper, background){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(wrapper).height();
var popupWidth = $(wrapper).width();
//centering
$(wrapper).css({
"position": "fixed",
"top": (windowHeight/2-100)-popupHeight/2,
"left": windowWidth/2-popupWidth/2,
"z-index" : "10000"
});
$(background).css({ "height": windowHeight });
}
//event handlers
var trigger = "input.popup-trigger-delete";
var wrapper = "div.popup-wrapper-delete";
var background = "div.popup-background-delete";
var dtpbc = "input.popup-background-delete-cancel";
$(document).ready(function(){
$(trigger).click(function(){ centerPopup(wrapper,background); loadPopup(wrapper); });
$(dtpbc).click(function(){ disablePopup(wrapper, background); });
$(document).keypress(function(e){ if(e.keyCode==27 && popupStatus==1){ disablePopup(wrapper,background); } });
});
CSS
div.popup-background-delete { display:none; }
div.popup-wrapper-delete { display:none; }
div.popup-wrapper { position:relative; display:none; display:block; width:350px; height:245px; padding:0; margin:0; z-index:5000; }
div.popup-top { position:relative; display:block; background-color:#ffffff; width:350px; height:40px; padding:0; margin:0; z-index:5000; }
div.popup-middle { position:relative; display:block; background-color:#ffffff; width:350px; min-height:165px; padding:0; margin:0; z-index:5000; }
div.popup-middle .content { position:relative; display:block; margin:0 auto; padding-top:20px; padding-bottom:10px; width:255px; z-index:5000; }
div.popup-middle .controls .left { position:absolute; top:0; left:80px; z-index:5000; }
div.popup-middle .controls .right { position:absolute; top:0; right:80px; z-index:5000;}
div.popup-bottom { position:relative; display:block; background-color:#ffffff; width:350px; height:40px; padding:0; margin:0; z-index:5000; }
div.popup-background { position:absolute; top:0; left:0; width:100%; height:100%; z-index:5000; background-color:#cbcbcb; opacity:0.2; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=20)"; filter: alpha(opacity=20); -moz-opacity:0.2; }
In order to get above sample working (sorry, can't comment), do this:
Change asp button to html button
Change "popup-background-delete-track" to "popup-background-delete"
In centerPopup, replace $(background).css({ "height": windowHeight }); with $(background).css({ "display": 'block' });
Remove all references to display:block in the CSS.

Resources