Length validation of masked Input field

I have the following masked field:

<input id="phone1" placeholder="(___) ___-____"/>

masking is done like this:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
        <script>
        $("#phone1").inputmask({ "mask": "(999) 999-9999" });
        </script>

I want to do the length validation of the phone field. The phone field should be exactly 10 characters long or with masked input, it should be 14 characters long.
I don’t want to do the validation on submit button, but I want to do the length validation of phone field “onfocusout” or when someone tabs out of the field. I just want to display a message underneath the phone field saying “this field should be 10 characters long” if someone puts less than 10 character. This masking is not letting the user put more than 10 character. This phone field is not a required field.

any help will be highly appreciated.

after ajax call javascript oncall function no work

1.After ajax call,how to make javascript oncall work?
index.php

#this code no work 
        function sortTable(columnName){
        var sort = $("#sort").val();
        $.ajax({
            url:'fetch_details.php',
            type:'post',
            data:{columnName:columnName,sort:sort},
            success: function(response){
           
                $("#empTable tr:not(:first)").remove();
                
                $("#content").append(response);
                if(sort == "asc"){
                    $("#sort").val("desc");
                }else{
                    $("#sort").val("asc");
                } }});}

#this code work well

function getresult(url) {
    $.ajax({
        url: url,
        type: "GET",
        data: { rowcount: $("#rowcount").val() },
        success: function(data) {
            $("#pagination").html(data);
             
        },
        error: function() { }
    });
}

2.here work well if oncall itself only but when combine others can’t work

function scrollToTop() {
        window.scrollTo(0, 0);
      }



#here is print side
<div id="pagination">
<input type="hidden" name="rowcount" id="rowcount" />
</div>

<script>
getresult("getresult.php");
</script>

getresult.php

$output .='<th><span sortTable("cus_code");scrollToTop();>Code</span></th>';
print $output;

After ajax successful call,the onclick javascript no working
but when onlick scrollToTop only no problem

Onclick callback with fetch method in Html language

I have the following html code:

<!doctype html>
<html>

<head>
    <title>Online Strategy</title>
</head>

<body>
    <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
    <form action='/result' method=POST target="dummyframe">
        <textarea id="editor" name="name"></textarea>
        <button type=submit>Run</button>
    </form>
    <textarea id="editor2" name="nam2"></textarea>
    <script>
        function GetData() {
            console.log("my ssss");
            fetch("/result")
                .then((response) => {
                    var upperCase = response.json();
                    console.log("dddd");
                    var upperCase = upperCase.toUpperCase();
                    document.getElementById("outputText").innerHTML = upperCase;
                })
        }
    </script>
</body>

</html>

What I am trying to do is as following:

  1. I input some text in the first textarea, then I click the Run button, then in url 127.0.0.1/result, will have a respone
  2. I fetch the respone, and paste the body into the second textarea.

But it doesn’t work as expected, it has error 404 not found.

What am I doing wrong?

The server side is like this:

#![allow(unused_imports)]

use std::time;

use actix_web::{
    middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result,
    get,
    post,
    http::{
        header::{self ,ContentType},
        Method, StatusCode,
    }
};
use actix_files::Files;
use serde::{Serialize, Deserialize};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_html)
            .service(show_result)
    })
    .bind(("127.0.0.1", 8081))?
    .run()
    .await
}

#[get("/")]
async fn get_html() -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html")
        .body(include_str!("../form2.html"))
}

#[post("/result")]
async fn show_result(params: web::Form<InputCodes>) -> impl Responder {
    let mut res = format!("your input is {}, and I have got it in {:?}", params.name, time::Instant::now());
    HttpResponse::Ok()
        .content_type("text/plain")
        .body(res)
}

#[derive(Serialize, Deserialize)]
pub struct InputCodes {
    pub name: String
}

which is some rust codes. The function show_result handle the form post, and write some word into the /result webpage.

Avoid being affected by website’s default CSS or JS

I use Tampermonkey to write a JS script in a website.

It should be on the right of the website’s page like this.Correct style

And it’s correct in one path of the website. But when I use the same script on another path of the website. It has a wrong style like this.Wrong style

The elements added by my script isCode

I’ve tried to put it in Shadow DOM. But it doesn’t work.

My tampermonkey script just contain createElement and some style, so I may not show it.

Can anyone help me with this problem please?

Expecting the problem could be solved.

Checking if jasmine test is called with a done callback

I’d like to replace some functions inside of test environment to make sure that they’re only called inside test with done callback available. This is to catch (for example) cases where setTimeout is used in a test which does not wait for completion. I’m trying to achieve something like UnhandledPromiseRejection here, but for timers.

But the part I can’t figure out is: How would I check if the test I’m currently running is using the done callback or not? (in a function down the stack, not in the test itself)

How to get an image from user on webpage and store this image in sql server database using asp.net?

I am making a website with profiles of users and there they can upload their avatar. And I need to get a photo from user and store this in users database. First got an image from user and send information to server:

    saveButton.onclick = (() => {
        const file = photoInput.files[0];
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = (async () => {
            const bytes = reader.result;
            const description = descriptionInput.value;
            const data = JSON.stringify({
                photo: bytes,
                description
            });

            await fetch("[username]/changedata", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },

                body: data
            });

            window.location.reload();
        });
    });

Then tried to store this image in users database:

        app.MapPut("{username}/changedata", async (string username, HttpContext context) =>
        {
            var data = await context.Request.ReadFromJsonAsync<UserDataChange>();
            using var con = new SqlConnection(connection);
            await con.OpenAsync();
            var command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "UPDATE [users] " +
                                  "SET description=@description, picture=@picture " +
                                  "WHERE username=@username";
            command.Parameters.AddWithValue("username", username);
            command.Parameters.AddWithValue("description", data.Description);
            command.Parameters.AddWithValue("picture", data.Photo);
            await command.ExecuteNonQueryAsync();
            await con.CloseAsync();
        });

UserDataChange class:

public class UserDataChange
{
    public byte[] Photo { get; set; }
    public string Description { get; set; }
}

But byte[] is invalid type for this situation.

How to add sliding effect for accordion menu in Javascript?

I am creating an accordion menu which slides up and down on clicking on it. I am able to get the functionality but couldn’t get the animation effect that slides smoothly from top to bottom and bottom to top while showing and hiding the menu content.

I’ve tried jQuery functions like slideUP() and slideDown() but I want to achieve it through javascript.
Here is my code..

<div class="accordian-wrapper">
    <div class="accordian-hover d-flex flex-row justify-content-center align-items-center container">
      <div id="accordian-question-div">
        <h5>How to use this product ?</h5>
      </div>
      <div>
        <i class="fa fa-solid fa-arrow-down"></i>
      </div>
    </div>
    <div class="accordian-content">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt iste est sunt? Excepturi quas, sunt recusandae laboriosam eligendi cum autem. Tempora nulla, at sequi minima praesentium, explicabo ullam eius odio corporis optio autem pariatur consequuntur, rem voluptate soluta exercitationem natus quod repudiandae. Reprehenderit vitae, iste facere aspernatur minima modi repellat!</p>
    </div>

  </div>
let k=0;
let rightArrow=$(".fa-arrow-down");
$(".accordian-hover").click(() => {

  if (k==0) {
    $(".accordian-content").show();
    k=1;
    rightArrow.toggleClass("fa-arrow-down fa-arrow-up");
  }
  else{
    $(".accordian-content").hide();
    k=0;
    rightArrow.toggleClass("fa-arrow-up fa-arrow-down");

  }



});

JS: build object based on given object parent’s property?

I am trying to create a JS object that hold all the urls.

I am trying to achieve this so I have a data() part:

export default defineComponent({
  name: 'MyPage',
  data() {
    backendUrls: {...}
  }
})

In a more simple way it would look like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }
  userAdd: function() { return this.baseUrlWithPrefix() + "/user/add"; }
}

I could use the this keyword since it pointed to the same object where the given property also exists.

But I would like to split a bit more and create objects in the object:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: ...
  },
  socketUrls: {
    messageUrls: {
      userAdd: ...
    }
  }
}

Here if I try generalUrls: { baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }}, it won’t work because it does not find the baseUrl since the this keyword points on the generalUrls object and not the backendUrls object where the baseUrl exists.

I’d need something like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: function() { return {goBackToParentObject}.this.baseUrl + "/ver1"; }
  },
  socketUrls: {
    messageUrls: {
      userAdd: function() { return {goBackToParentObject}.this.generalUrls.baseUrlWithPrefix() + "/user/add"; }
    }
  }
}

Change the color of a button, if at least one option of a form is selected

I have a form with three options, by default the button is disabled in gray, I want that if the user just chooses an option, this button changes to blue.

<div id="openModal" class="modalDialog" data-modalorder="1">
<div>
<a href="#close" title="Close" class="close">X</a>
<h1 style="text-align: center; font-weight: 600">Gender</h1>
<form id="form_gender">
    <div class="hungry">
        <div class="selection">
            <input id="man" value="Man" name="gender" type="radio" /> 
            <label for="man">Man</label>
        </div>
        <div class="selection">
            <input id="woman" value="Woman" name="gender" type="radio" />
            <label for="woman">Woman</label>
        </div>
        <div class="selection">
            <input id="other" value="Other" name="gender" type="radio" />
            <label for="other">Other</label>
        </div>
    </div>
    <input id="btn_genero" class="getAssignment" type="button" onclick="btnGenero()" value="Siguiente">   
    </form>
</div>

I have the following function to add the new class with the new color, but it doesn’t work correctly. When I select an option the color does not change to blue

<script>
const btnGenero = () =>{
            
            try{
              const value = document.querySelector('input[name="gender"]:checked').value;
              var element = document.getElementById("btn_genero");
              if(value != ''){
                element.classList.remove("getAssignment");
                element.classList.add("getAssignment2");
                alert('success')
              }else{
                alert('required')
              }
            }catch(err){
              alert('required')
            }
            
          }
</script>

And this is my css code

<style>
.getAssignment {
cursor: pointer;
background: gray;
border: none;
border-radius: 25px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
padding: 5px 30px;
margin-top: 10px;
width: 259px;
height: 34px;
}
.getAssignment2 {
cursor: pointer;
background: red;
border: none;
border-radius: 25px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
padding: 5px 30px;
margin-top: 10px;
width: 259px;
height: 34px;
}

Removing fixed height makes the slider collapse intially when it loads

I have created a very simple responsive slider with vanilla JavaScript. It works great but has one issue which I am not able to figure it out. I am hoping someone from this community can help me.

Below is the slider demo I have in CodePen

CodePen Link

What I am trying to do is to remove the fixed height I have on .pc-mslider container, if I remove the fixed height the slider is collapsed when is it loaded due to the fact the height is not set. If I set the height and resize the window, it looks whacked either with huge space at the bottom or the content is hidden.

I am looking a way to fix this.

Thanks

I tried removing the height and calculating the height based on first slide using the code below

// Set the initial height based on the first slide
const slider = document.querySelector('.pc-mslider');
const firstSlideHeight = slides[0].offsetHeight;
slider.style.height = `${firstSlideHeight}px`;

But this is not working as it adds inline style height:0px .pc-mslider

JS function to append an external icon and how to position it

I’m trying to create a JS function that appends an icon(from font-awesome(I got it linked to the html file)) to the far-right side of the “li” row when the mouse hovers on it. But something seems off that it doesn’t work.

The list itself. It has hover properties.

The JS function in question.

const liElement = document.querySelectorAll("li")

   function appendIconToLi(liElement) {

    const iconDOM = document.createElement('icon');
    iconDOM.classlist = `<i class="fa-thin fa-house"></i>`

    liElement.addEventListener('mouseenter', () => {
      liElement.appendChild(iconDOM);
    });
    liElement.addEventListener('mouseleave', () => {
      liElement.removeChild(iconDOM);
    });
   }

HTML section looks like this

    <ul id="DadsList">
      <li>3 liters of Milk</li>
      <li>Bread</li>
    </ul>

CSS for ul.

  ul {
    margin: 0;
    padding: 0;
  }
  
  ul li {
    cursor: pointer;
    position: relative;
    padding: 12px 8px 12px 40px;
    background: #eee;
    font-size: 18px;
    transition: 0.2s;
    list-style-type: none;
  
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  
  ul li:nth-child(odd) {
    background: #f9f9f9;
  }
  
  ul li:hover {
    background: #ddd;
  }
  
  ul li.checked {
    background: #276678;
    color: #fff;
    text-decoration: line-through;
  }
  
  ul li.checked::before {
    content: "";
    position: absolute;
    border-color: #fff;
    border-style: solid;
    border-width: 0 2px 2px 0;
    top: 10px;
    left: 16px;
    transform: rotate(45deg);
    height: 15px;
    width: 7px;
  }

I’m slightly lost on how to style an element in JS. Example is to position it to the far right of the “li” element as mentioned above.