Making radio buttons required on the check of the checkbox

I have a check box on my web page with two radio buttons underneath it and two text boxes. The screen shot is below:

enter image description here

below is my code for checkbox. I want two radio button and two text boxes to be required if the checkbox is checked.

  3. <input id="employ"  asp-for="Employments.Sec3Employed" type="checkbox" /> This is the test for employment agency.

I have a class name called “OutEmploy” for each radio button and each input box like this:

 <div class="col-sm-2">
                        @foreach (var rep in Model.Employments.reported)
                        {
                            <input class="outEmploy" type="radio" asp-for="Employments.Reported" value="@rep" />
                            @rep
                            <span style="margin-right:5px"></span>
                        }
                    </div>
                      <div class="form-group row">
                    <div class="col">
                        <input asp-for="Employments.PositionTitle" class="outEmploy form-control " />
                    </div>
                </div>

     <div class="form-group row">
                    <div class="col">
                        <input asp-for="Employments.PositionTitle" class="outEmploy form-control" />
                    </div>
                </div>

Below is the Jquery function that I am running in order to make radio buttons and text box to be required:

<script> 
           $(function(){
              
            $('#employ').on('click', function () {
                if($(this).is(':checked')){

                    $('.outEmploy').attr('required', 'required');
                }else{

                    $('.outEmploy').removeAttr('required');
                }
     
            });
        }); 
 
  </script>

when I click on the check box, the radio button and two text boxes should be required. Right now, when I click on the check box, two text boxes become required, but the radio button does not become required. Not sure, what am I doing wrong.

Any help is appreciated.

Cross Browserrendering of speechSynthesis.getVoices()

So far I have this code:

speechSynthesis.addEventListener("voiceschanged", () => {
    const voices = speechSynthesis.getVoices()
    voices.forEach((v) => {
        var list = document.getElementById("voices")
        const item = document.createElement("li")
        item.innerText = "Language Code: " + v.lang + ", Voice Name: " + v.name
        list.appendChild(item)
    })
})
const voices = speechSynthesis.getVoices()
voices.forEach((v) => {
    var list = document.getElementById("voices")
    const item = document.createElement("li")
    item.innerText = "Language Code: " + v.lang + ", Voice Name: " + v.name
    list.appendChild(item)
})

As you can see, I’m essentially doing the same thing inside and outside of the eventListener. Safari renders the list without the eventListener block, but not Chrome or Firefox on macOS. Research showed me that I needed to put it inside an eventListener. Doing that only rendered it in Chrome. Adding a copy of the code below the event Listener rendered it in both Firefox and Safari.

But I also know it’s not good to keep repeating yourself, so I’m trying to find a way I can get this list across browsers and then do something with it (like I did with the forEach and rendered it to the page–but I’m actually working on a voice select menu.

So making two copies of the menu within the JavaScript wouldn’t be practical at all.

Any idea how to work with this issue?

Getting confirmation via Bootstrap Modal before submitting the form

I am developing a website. Part of this website is an edit-form. When users want to submit their changes, I want a Bootstrap modal to appear and ask for confirmation.

enter image description here

The form itself is HTML and the submit process is managed by a PHP code.

<form method='post' id='submitForm' >
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline">
                                        <label class="form-label ">Firstname</label>
                                            <input type="text" name="firstname" value="<?php echo $firstname;?>" class="form-control my-5">        
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Lastname</label>
                                        <input type="text" name="lastname" value="<?php echo $lastname;?>" class="form-control my-5">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Fullname</label>
                                        <input type="text" name="fullname" value="<?php echo $fullname;?>" class="form-control my-5">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Status</label>
                                        <select class="form-control my-5" name='status' id="exampleFormControlSelect1">
                                            <option <?php if ($status == 'Active') echo 'selected="selected"'; ?>>Active</option>
                                            <option <?php if ($status == 'Inactive') echo 'selected="selected"'; ?>>Inactive</option>
                                        </select>
                                    </div>                            
                                </div>
                                
                            </div>
                            <div class="row">
                            <div class="col-md-2">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Employee No.</label>
                                        <input type="test" name="empid" value="<?php echo $empid;?>" class="form-control my-5" >
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">BPM Employee No.</label>
                                        <input type="test" name="newempid" value="<?php echo $newempid;?>" class="form-control my-5">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                <div class="input-group input-group-outline ">
                                    <label class="form-label">Email Addr.</label>
                                    <input type="test" name="email" value="<?php echo $email;?>" class="form-control my-5">
                                </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Project</label>
                                        <select class="form-control my-5" name='project' id="exampleFormControlSelect1">
                                            <?php
                                                    foreach ($projects as $projectName){
                                                            $projectList = $projectName->project;
                                            ?>
                                                <option <?php if ($projectList == $project) echo 'selected="selected"'; ?>><?php echo $projectList?></option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group input-group-outline ">
                                        <label class="form-label">Manager</label>
                                        <input type="test" name="manager" value="<?php echo $manager;?>" class="form-control my-5">
                                    </div>
                                </div>
                                
                                
                            </div>

                            </div >
                            <div class="row">
                                <div class="col-md-11">
                                </div>
                                <div class="col-md-1">

                                <div class="row">
                                    <div class="col-md-4">
                                        <button type="submit" name="submit" id= "submit-button" class="btn btn-block bg-gradient-success mb-3 update" 
                                        data-bs-toggle="modal" data-bs-target="#"   
                                        >Update</button>
                                        
                                        </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            
                        </form>

Here is the modal:

<div class="modal fade" id="user-info-edit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title font-weight-normal" id="exampleModalLabel">Please confirm</h5>
        <button type="button" class="btn-close text-dark" data-bs-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p class="" id="">Are you sure you want to submit changes? </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn bg-gradient-secondary" data-bs-dismiss="modal">Close</button>
        <!-- <button type="button" class="btn bg-gradient-success">Submit</button> -->
        <a href="" id="submit" class="btn btn-success">Submit</a>
      </div>
    </div>
  <//div>
</div>

The first thing that came to my mind was to stop the “submit”, when the submit button of the form is clicked and instead that trigers the Modal and then when the user clicks on the Submit button of the Modal, the form is being submitted. So I wrote this JS code:

<script>
    $(document).ready(function() {
        $('#submit-button').on('click', function(){

            submitForm.addEventListener('submit', (event) =>{
            event.preventDefault();
            })

            $('#user-info-edit').modal('show');
        });

        
    });



    $(document).ready(function() {
        $('#submit').on('click', function(){

            submitForm.submit();
        });
    });

 </script>

Now the Modal is shown but the form is not submitted. I read all I found relevant but none helped.

How do I make it so when I press a button in JS, an image appears?

I’m trying to learn programming, and I code things to practice and for fun. I tried to code it where when I click a button the button the text turns red. It worked but when I tried to make it add an image it didn’t work.

Here’s what I tried

<button onclick="TurnRed()">Redify</button>

    <script>
        function TurnRed() {
            let x = document.getElementById("Lorem");
            x.style.color = "red";
            var img = document.createElement("img");
            img.src = /HTML_Code/Ispum.webp;
            var src = document.getElementById("header");
            src.appendChild(img);
            <div id="header"></div>
        }
    </script>

How would you display Data from the API to the User after they have typed in their specific information?

I am currently making a simple website using React that lets you type in your motorcycle’s Make, Model, and Year. When you type those in you hit “Find Motorcycle.” The current issue is trying to get the Motorcycle data from the API and Display it to the user.

import React from 'react'
import './App.css'
import Model  from './Model'
import Button from './Button'
import Year from './Year'

function App() {



  return (
    <div>
      <h2>Make: </h2>
      <input></input>
      <Model />
      <Year /> <br></br>
      <Button />
    </div>
    )
}

export default App
import React from "react";
import  Axios  from 'axios'

function Button () { 
    
    return (
        <div> 
            <button onClick={findMotorcycle}>Find</button>
        </div>
    )
}


    const findMotorcycle = () => {
        Axios.get("'https://motorcycle-specs-database.p.rapidapi.com/article/2012/BMW/F%20800%20GS%20Trophy'").then((response)=>{
            console.log(response.data.content);
        })
    }

export default Button

How do I show details of a loading process while data is loading in useEffect?

When a particular custom React component I have first mounts, it uses useEffect to kick off a long multistep process of loading data that it will then render. The component isn’t always rendered, so this expensive process isn’t always needed. The process also makes some exotic calls through libraries that aren’t especially amenable to standard caching libraries like Axios or React Query.

I also have a progress display component and functions which can be called to update the state of progress display; these functions are passed into the long multistep process and called periodically to keep the user updated as various steps are completed. The objective is to allow the user to accurately distinguish between a process just taking a while because it has so many steps and a hang (the first often just looks like the second, but the second remains possible).

However, the updates to the state of the progress display get automatically batched up during the whole long process and thus the intended ongoing communication to the user doesn’t correctly happen. If I try to use flushSync around those updates I get a warning that “flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering.” The states are then still not correctly updated right away as steps are completed.

While the error makes sense, is there a canonical (or if not, at least working) way around this that allows one component’s state to be updated (and the component to be re-rendered) several times while another component’s componentDidMount() lifecycle hook is running?

Custom Error page not working in ASP.Net MVC 4.8 project when using jQuery Ajax

NET MVC 4.8 project. I have customer error page that works as expected and shows up when there is an error.

But one of the functionality is not working. There is an Action Method which invokes from jQuery Ajax function. In the Action Method I am generating an error but code returns to the calling page and shows the View instead of redirecting to Error page upon error.

See the below code:

public JsonResult RequestUpdate(TravelAuthorizationViewModel travelAuth)
{

        try
        {
            bool upadteResult = false;
           //works fine when return true but when the the below call to UpdateSerivce throws and error.  And in catch block here the error get caught and throws and error. 
            upadteResult = this.UpdateServices.UpdateEntry(travel);
            
            return Json(new { Status = upadteResult ? "Success" : "Error" }, JsonRequestBehavior.AllowGet);
        }
        catch(Exception e)
        {
            throw;
        }
    }

Ajax

   SubmitFormDataForEdit: function (formData) {
    $.ajax({
        url: "../Update/RequestUpdate",
        type: "POST",
        dataType: "json",
        data: { travel: formData },
        success: function (data) {
            if (data != null) {
                if (data.Status == "Success") {
                   // location.reload();
                    $('#successMsg').removeClass('hidden');
                    $('#successMsg').html("The Request has been saved.");
                    
                }
                else{
                    $('#successMsg').addClass('hidden');
                    $('#successMsg').html("");
                }
            }
        }
    })
}

Editing a form with Sveltekit

I’ve got an Artist page in sveltekit. It’s route looks like the following:

routes
    artists
        [slug]
            +page.server.js
            +page.svelte
        new
            +page.server.js
            +page.svelte
...

I’ve abstracted the form itself into a component called ArtistForm.svelte, for the purposes of this issue I’ll show just one field:

<script>
    export let formData;
    export let mode = "new";

</script>

<form method="POST" use:enhance>
    {#if (mode !== "new") }
        <input type="hidden" name="id" value={ formData.id } />
    {/if}

    <!-- Row 1: name, type -->
    <div class="flex flex-row">

        <div class="basis-1/2 form-control w-full">
            <label class="label">
                <span class="label-text">Name <span class="required-field">*</span></span>
            </label>
            <input
                    name="name"
                    id="name"
                    type="text"
                    value={ formData?.name || "" }
                    class="input input-bordered w-full max-w-xs"/>
            {#if formData?.errors?.name}
            <label for="name" class="label">
                    <span class="label-text-alt text-error">{ formData?.errors.name[0]}</span>
            </label>
            {/if}
        </div>
   </div>
   <div class="flex flex-row">
        <button type="submit" class="btn btn-primary">{ mode == "new" ? "Save" : "Update" }</button>
    </div>

</form>

So in artists[slug]+page.svelte I’ve simply got:

<script>
    import ArtistForm from "../../../components/forms/ArtistForm.svelte";

    /* data returned from load function in +page.server.js */
    export let data;

    /* data returned from actions in +page.server.js */
    export let form;

</script>

<ArtistForm formData={data} mode="edit" />

and in artistsnew+page.svelte I’ve got:

<script>
    import ArtistForm from "../../../components/forms/ArtistForm.svelte";

    /* data returned from actions function in +page.server.js */
    export let form;

</script>

<ArtistForm formData={form} mode="new" />

So far so good. The issue comes when validating the data. So the action for new looks something like:

export const actions = {
    default: async ({ request }) => {

        const data = Object.fromEntries(await request.formData());
        const artist = artistDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (artist?.errors && !emptyObject(artist.errors)) {
            return artist;
        }

        const response = await createArtist(artist);

        return {
            ...artist,
            "errors": response.errors,
        }
    }
};

If there are any validation errors it will return the fields plus the errors in an object.

For edit mode ([slug]) the action looks similar to the previous one.

When an error occurs on new, then the object returned from the action is assigned to formData so the entered fields are populated again plus there’s gonna be an errors object from which errors will be displayed.

With the new form there are no issues.

But with the edit form ([slug]), I’ve got issues. When the page first loads then the object returned from the load method is assigned to formData so the form is populated with that data, but when the form is submitted, then if any errors are encountered and returned from the action, that object will be assigned to form and not to data, and form is not being passed into ArtistForm, but even if I decided to pass it, I’d need to know when to pull data from data and from form.

How can I achieve that? Not sure if the question is not clear, please let me know if more details are needed.

Thanks

unable to access bootstrap 5 modal.show(), bootstrap not found

Please I am trying to display an edit modal and The issue is that in this line of code var modal = new bootstrap.Modal(modalWrapper.querySelector(".modal")); bootstrap is not defined. I have imported the cdn to my index.hmtl. I have checked other post and they to import the cdn. This is how I imported the cdn in the head section of the html. Initially I did the script in the body, I changed it to check why it was not working

<link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
      crossorigin="anonymous"
    />
    <script
      defer
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
      crossorigin="anonymous"
    ></script>

This is the code I wrote to display the modal

import React from "react";

const editProduct = () => {
  let modalWrapper = null;
  const showModal = () => {
    modalWrapper = document.createElement(
      "div"
    ).innerHTML = `<div class="modal fade modal-dialog modal-dialog-scrollable" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>
`;
    document.body.append(modalWrapper);
    var modal = new bootstrap.Modal(modalWrapper.querySelector(".modal"));
    modal.show();
  };
};

export default editProduct;

Help will be appreciated, thanks

Node JS, Using getAccounts() from inside getInitialProps

Is it possible use web3.eth.getAccounts() from inside the getInitialProps? When I run it it returns an undefined object. It works perfectly everywhere else in the code.

I want to use it to fetch some data from the solidity contract so it requires the user address to get the correct information. I then use this data to display on the page when it loads up.

Is there any other way to achieve this?

I hope my explanation is clear enough.

I am struggling to find any solution to this.
Thanks

VS code error: ‘node’ is not recognized as an internal or external command, operable program or batch file

I want to setup javascript for VS code. I’m pretty sure that I’ve done all of the steps needed to setup that is:

  1. Download javascript from the official website.

  2. Download the neccessary extensions from VS code.

But when I try to run the code, the compiler gives me this error:

'node' is not recognized as an internal or external command,
operable program or batch file.

[Done] exited with code=1 in 0.091 seconds

I’m using Windows 10.

What’s wrong?

CSS: expand items in grid on click to its actual content size

I am pretty new to web design and now I am struggling with some designing issues.

I try to do following thing:

  • two dimensional array of items that have fixed size
  • the items have hidden content, so they expand by click
  • clicked item expands until the content is shown (but no more than 100% width or 100% height)
  • when clicked item expands, it should fill the width of 1 row. If there are items on the left side, the clicked item should switch to next row and fill it. Items to the right side should be pushed into the next row.

First the part which works:
This is the table:

<div class="table-view">
    <my-item class="item"></my-item>
    <my-item id="one" class="item"></my-item>
<my-item class="item"></my-item>
<my-item class="item"></my-item>
</div>

table styling:

.table-view {
    box-sizing: border-box;
    display: flex; 
    flex-wrap: wrap;
    
    gap: 1rem;
    padding: 1rem;
}
.item {
    max-width: 100%;
    background-color: green;
}
#one {
        background-color: red;
    flex-basis: 0;
}

JS part

class ItemTable extends HTMLElement {
    constructor() {
        super();

        this.attachShadow({mode: "open"})
        this.shadowRoot.appendChild(tableTpl.content.cloneNode(true))

        this.item = this.shadowRoot.getElementById('one');
        this.item.addEventListener('click', () => {
                this.shadowRoot.getElementById('one').style['flex-basis'] = '100%'
            this.item.setFocus(true)
        })
    }
}

window.customElements.define('item-table', ItemTable)

Now the difficult part – the item itself:

<div class="item-wrapper">
    <div id="close-btn">
        <div class="extendable">here is close button</div>
    </div>
    <div class="item-small">
        <div id="avatar">here is an avatar</div>
    </div>
    <div id="item-name">display name</div> 
    
    <div class="extendable hidden-content">hidden content</div>
</div>

styling

.item-wrapper {
    min-width: 16rem;
    min-height: 18rem;
    
    //keep the items small until clicked
    max-width: 16rem;
    max-height: 18rem;
    
    display: flex;
    flex-direction: column;
}
.item-small{
    width: 16rem;
    height: 16rem;
}
#item-name{
    box-sizing: border-box;
    height: 2rem;
    text-align: center;
    padding-top: 0.3rem;
    font-size: 1.2rem;
}
.extendable {
    display: none;
}
#avatar {
    height: 16rem;
    width: 16rem;
}
#close-btn {
    align-self: flex-end;
}
#close-btn {
    align-self: flex-end;
}
/*mock hidden content for testing purposes*/
.hidden-content{
    width: 18rem;
    height: 46rem;
    border: thick groove black;
}
class MyItem extends HTMLElement {
    constructor() {
        super();

        this.attachShadow({mode: "open"})
        this.shadowRoot.appendChild(itemTpl.content.cloneNode(true))


        this.item = this.shadowRoot.querySelector('.item-wrapper');
        this.extendables = this.shadowRoot.querySelectorAll('.extendable')
        this.itemName = this.shadowRoot.querySelector('#item-name')
    }

    static get observedAttributes() {
        return ['is-focused']
    }

    attributeChangedCallback(attrName, oldVal, newVal) {
        if (attrName === 'is-focused') {
            if (newVal === 'true') {
                this.showContent()
            } else {
                this.hideContent()
            }
        }
    }

    setFocus(focus) {
        this.setAttribute('is-focused', focus)
    }

    showContent() {
            this.itemName.style['display']='none'
        this.extendNpcSheet()
    }

    hideContent() {
        this.itemName.style['display'] = 'none'
    }

    extendNpcSheet(){
        this.extendables.forEach(e => {
            e.style['display'] = 'block'
        })
    }
}

window.customElements.define('my-item', MyItem)

Here is an link to example how it look like at now:

https://jsfiddle.net/zap08tb7/

as you can see, the “hidden-content” does not expand in height. And the element does not expand to its content size, but to 100% of the width. I have no idea how I could achieve that. I am happy about any hint that you can give me.