I am trying to send id to Controller with a dynamic button but it is not working

I’m trying to send the id of the object to the controller with the button. But it only does this for an item in the first row of the list. The button does not work for other items in the list. How can I solve the problem?

$(document).ready(function(){       
            $("#showTweet").click(function(){
         var tweetId = $(this).parent().attr('id');
        $.ajax({
        
        type: "GET",
        dataType: "json",
        url: "http://localhost:8020/showTweet?tweetId="+tweetId,
        success: function(result){
            var description = result.description;
            $('#tweetText').text(description);
            
             }
        });
    });
    
<table id="myTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th>Kullanıcı</th>
                                <th>Oluşturulma Tarihi</th>
                                <th>Seçenekler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="unapprovedTweets: ${unapprovedTweets}">
                                <td th:text="${unapprovedTweets.creative}"></td>
                                <td th:text="${unapprovedTweets.create_date}"></td>
                                <td>
                                
                                    <div th:id="${unapprovedTweets.id}"
                                        style="width: 0px; height: 0px; display: contents;">
                                        <a id="showTweet" class="btn btn-warning">Tweeti Gör</a>
                                        
                                        
                                    </div> <a th:href="@{'/sendTweet/' + ${unapprovedTweets.id}}"
                                    class="btn btn-primary" style="width: 90px; margin-left: 5px;">Onayla</a>
                                    <a th:href="@{'/refuseTweet/' + ${unapprovedTweets.id}}"
                                    class="btn btn-danger" style="width: 90px; margin-left: 5px;">Reddet</a>


                                </td>

                            </tr>
                        </tbody>
                    </table>

JS add event handler using for loop, passing self as parameter not working

I am wondering why the statement “let im = _imgs[i];” is indispensable in this situation.
Essentially, the _imgs are an array of image elements. But if I add the eventhandlers by _imgs[i].addEventListener("click", function(){clickImage(_imgs[i]);}, false);, it won’t work.

Can anyone explain why? Thanks a lot!

function init()
{
    _imgs = document.querySelectorAll("#block2 img");
    console.log(_imgs.length);
    _clicked = new Object();
    for(var i = 0; i < _imgs.length; i++)    
    {      
        let im = _imgs[i];
        _imgs[i].addEventListener("click", function(){clickImage(im);}, false);
        _clicked[_imgs[i].id] = 0;
    }
    console.log("hi");
}

How to add a notification text in an HTML link and remove when clicked?

I’m creating a website which has daily news updates with URL links. I need to add a NEW! text on top of the link and once the user has visited it, need to remove the text. I searched for it everywhere what this feature is called and also went through anchor tag attribute in CSS i.e. a:visited {}, but it’s only CSS, how can I use for the above scenario?

Also if there’s any other way to deal with newly added links and after certain time, the NEW! text is gone, please let me know, I’m unable to find any resources online. Thanks.

fetch http request succeeds in Chrome and Firefox but fails in Safari

If we run the following code in safari it fails saying “failed to load resource: cannot parse response”

fetch('https://mycompanyname/service/contracts-api/operatingMode', {
  method: "GET",
  headers: new Headers({
    'Authorization': 'Basic VGVzdFVzZXIxOlRFU1QhdXNlcjE=',
    'X-mycompanyname-ContractsServer': 'someurl'
  })
}

safari inspect element preview

safari inspect element headers
But if we run the same code in Chrome or Firefox, it succeeds (in the same mac computer).

Is there any quirk in Safari fetch request that I am not considering?

event not trigger on first click parent Childs

I am creating hierarchy relations list with parent Childs and sub-childs if i checked parent then all Childs with checked but i clicked on Childs then sub-childs will be checked. everything is working fine but its work on second click not working on first click.
here is my fiddle example.
fiddle link here http://jsfiddle.net/fahadsheikh/qdkwy0s7/8/

function changeCategoryStatus(_this, id) {

var main = document.querySelector(".main-checkbox"+id);
var children = document.querySelectorAll(".sub-checkbox"+id);

function toggleCheck() {

  var array=[];
  children.forEach(child => {
    if($(this).prop("checked") == true){
        child.checked = child.checked = true
    }
    else if($(this).prop("checked") == false){
        child.checked = child.checked = false
    }

    
    array.push(child.value);
    
  })

  return array;
}

if(main){
    main.addEventListener("click", toggleCheck);
}

//for sub-parent category

var sub_parent = document.querySelector(".sub-parent"+id);
var sub_children = document.querySelectorAll(".sub-checkbox"+id);

function toggleCheck() {

  var array=[];
  sub_children.forEach(child => {
    if($(this).prop("checked") == true){
        child.checked = child.checked = true
    }
    else if($(this).prop("checked") == false){
        child.checked = child.checked = false
    }

    
    array.push(child.value);
    
  })

  return array;
}

if(sub_parent){
    sub_parent.addEventListener("click", toggleCheck);
}

 
    var status = $(_this).prop('checked') == true ? 'active' : 'inactive';
    $.ajax({
        type: 'POST',
        url:"{{url('admin/categories-status')}}",
        data: {
            id: id,
            status: status,
            _token: "{{ csrf_token() }}"
        },
        success: function (result) {
        $("#status-success").show();
        $("#status-success").html(result.success);
        setTimeout(function() {
            $("#status-success").hide()
        }, 3000);
        }
    });

}
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;
}
<div class="sortable">
   <div class="group-caption">
       <li class="main-parent category-sortable main-item" data-parent="4" data-position="4" data-newposition="1">second room 
                <span class="buttons-align">
                <label class="switch">
                    <input class="main-checkbox4" type="checkbox" id="user-4"
                        onclick="changeCategoryStatus(event.target, 4);"
                        >
                    <span class="slider round"></span>
                </label>
                
                </span>
                <div class="move" id="item-move" ><i class="fa fa-bars" aria-hidden="true"></i></div></li>
                <ul class="group-items group-items-parent">
                                                                                <li class="group-item-parent category-sortable" data-parent="5" data-position="1" data-newposition="1">second-child room 
                    <span class="buttons-align">
                    <label class="switch">
                        <input class="sub-checkbox4 sub-parent4" type="checkbox" id="user-5"
                            onclick="changeCategoryStatus(event.target, 5);"
                            >
                        <span class="slider round"></span>
                    </label>
                    </span>
                    <div class="move"><i class="fa fa-bars" aria-hidden="true"></i></div></li>

                                                                                <ul class="group-items-child">
                                                                    <li class="group-item-child category-sortable" data-parent="6" data-position="1" data-newposition="0">second subchild
                                    <span class="buttons-align">
                                    <label class="switch">
                                        <input class="sub-checkbox4" type="checkbox" id="user-6"
                                            onclick="changeCategoryStatus(event.target, 6);"
                                            >
                                        <span class="slider round"></span>
                                    </label>
                                    </span>
                                    <div class="move"><i class="fa fa-bars" aria-hidden="true"></i></div></li>
                                                                                            </ul>
                                                                                                            </ul>
                </div>
                                                                                <div class="group-caption">
                <li class="main-parent category-sortable main-item" data-parent="7" data-position="4" data-newposition="2">third-room 
                <span class="buttons-align">
                <label class="switch">
                    <input class="main-checkbox7" type="checkbox" id="user-7"
                        onclick="changeCategoryStatus(event.target, 7);"
                        >
                    <span class="slider round"></span>
                </label>
                
                </span>
                <div class="move" id="item-move" ><i class="fa fa-bars" aria-hidden="true"></i></div></li>
                <ul class="group-items group-items-parent">
                                                                                <li class="group-item-parent category-sortable" data-parent="9" data-position="1" data-newposition="1">third-child 
                    <span class="buttons-align">
                    <label class="switch">
                        <input class="sub-checkbox7 sub-parent7" type="checkbox" id="user-9"
                            onclick="changeCategoryStatus(event.target, 9);"
                            >
                        <span class="slider round"></span>
                    </label>
                    </span>
                    <div class="move"><i class="fa fa-bars" aria-hidden="true"></i></div></li>

                                                                                <ul class="group-items-child">
                                                                    <li class="group-item-child category-sortable" data-parent="10" data-position="1" data-newposition="0">third-subchild
                                    <span class="buttons-align">
                                    <label class="switch">
                                        <input class="sub-checkbox7" type="checkbox" id="user-10"
                                            onclick="changeCategoryStatus(event.target, 10);"
                                            >
                                        <span class="slider round"></span>
                                    </label>
                                    </span>
                                    <div class="move"><i class="fa fa-bars" aria-hidden="true"></i></div></li>
                                                                                            </ul>
                                                                                                            </ul>
                </div>
                                                                
            </div>

thanks for help.

html form not grabbing correct variables from survey

I am building a survey form that gathers information from students, using HTML (open to using javascript too) and have found several examples online but none seem to be working. The survey form is currently just selecting these:

enter image description here

The survey should be selecting all options (first name, last name, living place, college choices, major, campus visit), and I don’t know how to fix this.

This is the survey and the code:

enter image description here

 <h3> Senior Survey </h3>
    <div class="w3-container">

      <script type="text/javascript">
        console.log("Prospective student form is about to be displayed.");
      </script>

      <form method="post" action="mailto:[email protected]" method="GET" enctype="text/plain" name="seniorsurvey">
        <table class="w3-table w3-blue" id="second-gradient">
          
          <tr>
            <td style="text-align: center";> 
            <p><b> Please enter your first and last names. </b></p>
            <input type="text" id="firstname" maxlength="60" placeholder="First Name:"/> 
            <input type="text" id="lastname" maxlength="60" placeholder="Last Name:"/>  
            </td>
          </tr>

          <tr>
            <td style="text-align: center";> 
              <p><b> Where do you live? </b></p>
              <input type="radio" id="peru" name="radiobutton" value="Peru">
              <label for="peru">Peru</label>

              <input type="radio" id="southamerica" name="radiobutton" value="SA">
              <label for="southamerica">South America</label>

              <input type="radio" id="unitedstates" name="radiobutton" value="USA">
              <label for="unitedstates">United States</label> 
            </td>
          </tr>

          <tr>
            <td>
              <fieldset style="text-align: center";>
                <p><b> What were your other top college choices? </b></p>
                <input type="checkbox" id="bentley" name="uni">
                <label for="bentley">Bentley U.</label>

                <input type="checkbox" id="brandeis" name="uni">
                <label for="brandeis">Brandeis U.</label>
                
                <input type="checkbox" id="boston" name="uni">
                <label for="boston">Boston U.</label>
                
                <input type="checkbox" id="babson" name="uni">
                <label for="babson">Babson U.</label>     
                
                <input type="checkbox" id="northeastern" name="uni">
                <label for="northeastern">Northeastern U.</label>               
              </fieldset>
            </td>
          </tr>

          <tr>
            <td style="text-align: center";> 
              <p><b> What is your prospective major? </b></p>
              <select name="majors" id="majors">
                <option value="un">undecided</option>
                <option value="cis">Computer Information Systems</option>
                <option value="fi">Finance</option>
                <option value="acc">Accounting</option>
                <option value="ci">Creative Industries</option>
                <option value="mkt">Marketing</option>
              </select>
              <br>
            </td>
          </tr>

          <tr>
            <td style="text-align: center";> 
              <p><b> When do you plan to visit campus? </b></p>
              <input type="date" id="start" name="visit-start" value="2021-10-25" min="2021-10-25" max="2030-12-31">
              <br><br>
            </td>
          </tr>

          <tr>
            <td style="text-align: center";> 
              <button type="submit" value="Submit College Info"> Submit </button>
              <button type="reset" value="Clear College Info"> Clear  </button>
              <br><br>
            </td>
          </tr>

        </table>
      </form>      

    </div>

Promise trouble! How can I write this in such a way that it waits for the end?

Trying to write this in a way that it will wait for the db operations to complete. Possible?

function addFriendsToSession(session, sessionId) {
    const friends = [];

    const incoming = session.users.forEach(async user => {
        console.log('user', user);
        await db
            .collection('users/' + user + '/settings')
            .doc(user)
            .get()
            .then(doc => {
                if (doc.exists) {
                    const returnObj = doc.data();
                    return returnObj.friends ? returnObj.friends : [];
                } else {
                    return [];
                }
            });
    });
    friends.push(incoming);
    return friends;
}

array elements does not match same assigned elements

I wrote a function where I am looping through an array(which contains a number of array elements itself).
e.g. theMainAr:[ [ 5 ],[ 5, 3 ],[ 5, 3, 9 ],[ 5, 3, 9, 4 ],[ 3 ],[ 3, 9 ],[ 3, 9, 4 ],[ 9 ],[ 9, 4 ],[ 4 ] ]
The main array I got the above array from is : weights: [5,3,9,4]
I want to get a combination from these above arrays like this:sameLenAr:[[5,9],[5,4],[5,3,4],[3,4]]
My code is:

let sameLenAr = []
    let inc = 0
    for(let i=1;i<theMainAr.length-3;i++){  
        let curLen = theMainAr[i].length
        if(curLen>1){
            let curAr = theMainAr[i]
            let curArLen = curAr.length
            let indexOfEle = weights.indexOf(curAr[curLen-1])
              for(let m=indexOfEle+1; m<lenOfWets;m++){
                //   console.log(a)
                 curAr[curArLen -1] = weights[m]
                 console.log(curAr)
                 sameLenAr[inc] = curAr
                 inc++
                }
        }
    }

But Everytime I get an output like this: [[5,4],[5,4],[5,3,4],[3,4]]
The first element is not [5,9]
Why?

Asp razor form not submitting on popup modal button click

I am using JavaScript to submit the popup dialog, but it’s not submitting.

here is my view, I have checked the javascript, it is firing up but the $(“form”).submit() statement is not doing anything and the next statement is executed.

@{ 
    ViewBag.Title = "Add Comment";
    Layout = "~/Views/Shared/Popup.cshtml"; 
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#SaveComment").click(function (e) {
            e.preventDefault();
            $("#form").submit();
            parent.HidePopup(true);
        });
    });
    </script>

@using (Html.BeginForm("CreateComment", "OnlineInventory", FormMethod.Post, new { id = "form"}))
{
    @Html.Hidden("OccupantInventoryRoomId", Model.OccupantInventoryRoomId)
    @Html.Hidden("OccupantInventoryItemId", Model.OccupantInventoryItemId)
    @Html.HiddenFor(m => m.AllocationId)
    @Html.HiddenFor(m => m.Status)

    @Html.TextAreaFor(m => m.Comment, new { Class="CommentTextBox" })
    <div class="Navigation">
        <input type="button" value="Cancel" onclick="parent.HidePopup(false)" />
        <input id="SaveComment" type="button" value="Save" class="InputButton"/>
    </div>
}

this is my controller

  public class OnlineInventoryController : Controller
    {
        [HttpPost]
        public ActionResult CreateComment(AddNewCommentModel model, int? allocationId)
        {
            User user = this.userProvider.GetByUserName(System.Web.HttpContext.Current.User.Identity.Name);

            if (!this.userProvider.IsAllowed(9, user.KxId))
            {
                return this.RedirectToAction("Index", "Inspections");
            }

            try
            {
                OccupantInventoryComment commentToSave = new OccupantInventoryComment
                {
                    Comment = model.Comment,
                    CommentDateTime = DateTime.Now,
                    CreatedByUserId = user.KxId,
                    OccupantInventoryRoomId = model.OccupantInventoryRoomId,
                    OccupantInventoryItemId = model.OccupantInventoryItemId,
                };
                ViewBag.OccupantInventoryRoomId = model.OccupantInventoryRoomId;
                ViewBag.OccupantInventoryItemId = model.OccupantInventoryItemId;
                this.occupantInventoryCommentProvider.Save(commentToSave);
            }
            catch (Exception ex)
            {
                this._audit.Add(Product.KxRoomCheckerBackOffice, Severity.Error, ActivityType.Create, new StackTrace().GetFrame(0).GetMethod().Name, string.Empty, string.Empty, ex);
            }

            return this.RedirectToAction(model.Status.ToString(), new InventoryModel { AllocationId = model.AllocationId, Updated = true });
        }
}

sqlMessage: “Unknown column ‘c.created’ in ‘field list'”

Im getting this error which I’m not completely sure how to solve.

    CommentModel.getCommentsForPost = (postId) => {
    let baseSQL = `SELECT u.username, c.comment, c.created, c.id
    FROM comments c
    JOIN users u
    on u.id=fk_authorid
    WHERE c.fk_postid=?
    ORDER BY c.created DESC`;
    return db.query(baseSQL, [postId])
        .then(([results, fields]) => {
            return Promise.resolve(results);
        }).catch(err => Promise.reject(err));
};

Error:

      code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sql: 'SELECT u.username, c.comment, c.created, c.idn' +
    '    FROM comments cn' +
    '    JOIN users un' +
    '    on u.id=fk_authoridn' +
    "    WHERE c.fk_postid='''1'''n" +
    '    ORDER BY c.created DESC',
  sqlState: '42S22',
  sqlMessage: "Unknown column 'c.created' in 'field list'"
}

Any help would be appreciated!

how do I copy background html code of a div

I’m making a free custom website creator tool with drag and drop.
One can make the desired page by dragging elements to a div section which is then reviewed.
I want the user to copy the code inside that div section so he may be able to use it.
I’m totally new to java so I don’t know how to do so.
Please help me that how can I copy The code inside a div. So, I may be able to help people to generate their own custom templates without paying a single dollar.

note: this is a static website so nothing is being done on the server.

discord.js v13 slash commands not setting

The way my slash command handler works is I iterate through all the current client guilds, add an object to an array with the keys ‘id’ and ‘commands’, id being an integer of the guild id and commands being an array.

Then, iterate through the commands directory, require the file, check if the slash command builder has a ‘guilds’ element, in which the code will iterate through the guilds element and add the command builder to every guild commands array in the beforementioned guild array.

Then, once all is complete, iterate through the guilds array, find the guild by id, commands.set. All is working, except it only adds the commands to one of the guilds. In the iteration forEach of the guild array, I’ve made it console.log the id of the guild, and console.log after the setting of the commands. Both log properly, no errors thrown, but only my original testing server has the commands registered, and not a new server that a friend owns.

Ensured all intents are valid, administrator issued and role is high as it needs to be. Super confused!

    let guilds = []

    client.guilds.cache.forEach(guild => {
        guilds.push({
            id: guild.id,
            commands: []
        })
    })

    function addToGuild(id, obj) {
        guilds.forEach(guild => {
            if (guild.id == id) {
                guild.commands.push(obj)
                return true
            }
        })
    }

    fs.readdirSync(`${process.cwd()}/commands`).forEach(file => {
        if (file.endsWith('.js')) {
            let requiry = require(`${process.cwd()}/commands/${file}`)
            if (requiry.command.guilds) {
                requiry.command.guilds.forEach(guild => {
                    addToGuild(guild, requiry.command)
                })
            } else {
                guilds.forEach(guild => {
                    guild.commands.push(requiry.command)
                })
            }
        }
    })

    guilds.forEach((guild) => {
        console.log(guild.id)
        client.guilds.cache.find(guild => guild.id == guild.id).commands.set(guild.commands)
    })

Trying to find biggest number of a input (javascript)

I’ve got a problema running now that is: I need a function that find the highest number made by consecutive digits within that number that I received by the parameter.
For example: If my input is 1235789 my output should be 789. If my input is 123689, my output should be 123.

function getbiggestNumber(numberInput) {
    const numberString = numberInput.toString(); // turned into string

    const temporaryResult = []; // create the array of possible solutions which i'd go through to find the highest value inside of it

    for (let i = 0; i < numberString.length; i += 1) {
        const temporary = [numberString[i]]; // create a temporary answer that would serve as a base

        for (let x = i + 1; x < numberString.length; x += 1) {
            const subResult = Number(numberString[i]) - Number(numberString[x]); // the result of the current number minus the following number

            if (subResult === -1) { // if they are in a sequence this should be -1
                temporary.push(numberString[x]); // pushing this number to that temporary answer
            } // here should be some condition for it to keep running, instead getting into another number of for loop
        }
        temporaryResult.push(temporary); //  pushing that temporary answer to the result, so I could keep track of it
    }
    console.log(temporaryResult); //  checking the output
}

The problem is that this code is only providing double digits inside a array, and that was the only way I found to do this.
I’d be really thankful if someone could give me a light on this.
Thanks!