Repeater issue/problm

We are trying to use this repeater:
https://www.jqueryscript.net/form/Form-Fields-Repeater.html

It seems there is problem if you look at the demo.
https://www.jqueryscript.net/demo/Form-Fields-Repeater/

Try on demo to add for example four groups.(press three times add button).

Then remove all four groups by pressing Delete button.

Then press add again to add a new group.

If you inspect the name element it is:

The problem is with test[4]name. Normally it should be test[0]name.

It seems that when you delete element does not delete the counting.

So if you play a little bit with delete/add buttons counting is wrong.

Javascript of this is :

    jQuery.fn.extend({
     createRepeater: function () {
         var addItem = function (items, key) {
        var itemContent = items;
        var group = itemContent.data("group");
        var item = itemContent;
        var input = item.find('input,select');
        input.each(function (index, el) {
            var attrName = $(el).data('name');
            var skipName = $(el).data('skip-name');
            if (skipName != true) {
                $(el).attr("name", group + "[" + key + "]" + attrName);
            } else {
                if (attrName != 'undefined') {
                    $(el).attr("name", attrName);
                }
            }
        })
        var itemClone = items;
        $("<div class='items'>" + itemClone.html() + "<div/>").appendTo(repeater);
    };
    /* find elements */
    var repeater = this;
    var items = repeater.find(".items");
    var key = 0;
    var addButton = repeater.find('.repeater-add-btn');
    var newItem = items;
    if (key == 0) {
        items.remove();
        addItem(newItem, key);
    }

    /* handle click and add items */
    addButton.on("click", function () {
        key++;
        addItem(newItem, key);
    });
}
 });

Have anyone ever used this repeater? or have a version of this that works correct?

Javascript Performance Test

I was just curious why javascipt have many methods to convert a string to number, exploring that i found at this website called jsBench.me. I am not sure what these kind of websites called but for me it was a website to compare the codes i write. While playing around,
enter image description here
I got a result which was a bit surprising for me. From what I understood this can be,

  1. Something I am not aware about.
  2. This website is a bullshit.
  3. I have some theories in my mind which supports this result, like it might me because javascript stores the value first in cache and blah blah blah..(I have no idea on how to explain what I think)

But I am not sure about anything, is there anyone who can help me understand this?

Javascript JSON not parsing properly

I’m trying to get data out of a reply given to me from a backend API. I have an object called result which contains the following reply from the server:

{
  connection: 'Keep-Alive',
  'content-language': 'en-GB',
  'content-length': '0',
  'content-type': 'text/html'
  date: 'Fri, 11 Mar 2022 06:41:06 GMT',
  'keep-alive': 'timeout=5, max=100',
}

I’m trying to get the ‘keep-alive’ part but I’m unsure how I can access it.

I’ve tried parsing result as JSON

const obj = JSON.parse(result)
console.log(obj)

But this throws the following error:

undefined:1
[object Object]
 ^

SyntaxError: Unexpected token o in JSON at position 1

The issue seems to be that connection and date aren’t within single quotes and I don’t know how to fix this.

TypeError: __init__() got an unexpected keyword argument ‘service’ error using Python Selenium ChromeDriver

When i am running the code on pycharm idle the code is going good without errors. when i converted #into exe file by using pyinstaller or auto-py-to-exe i am getting this type of error. #

#i am not getting where i have to change.#
”’

import time,datetime
from datetime import date
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pyautogui
from pywinauto.keyboard import send_keys
import calendar
import openpyxl
import tkinter as tk
from tkinter import *
from tkinter import messagebox as mb
from pywinauto import application
import pywinauto
import comtypes.client

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
'''

Preventing input submit from refreshing page

I would like to prevent my submit button from refreshing my page when I click submit.

This is what I have tried

const formSubmit = e => {
    e.preventDefault();
    const newSubmission = {
      x: horizontal,
      y: vertical,
      steps: count,
      email: email.trim(),
    }
    // console.log(newSubmission)
    postNewSubmission(newSubmission);
  }

and my input:

    <input id="submit" onSubmit={formSubmit} type="submit"></input>

For added context, clicking on submit should send some data to an API and receive some response hence why I am calling postNewSubmission.

To reiterate, the issue is that everytime I click submit it refreshes my page – which is not I what I want – I would like to prevent this default behavior

Can anyone explain a part of the moment.js diff method logic?

Can anyone explain how the logic in moment.js’s monthDiff works? Here’s the excerpt of diff function.

function monthDiff(a, b) {
    if (a.date() < b.date()) {
        // end-of-month calculations work correct when the start month has more
        // days than the end month.
        return -monthDiff(b, a);
    }

    !!! I DON'T UNDERSTAND FROM HERE BELOW !!!

    // difference in months
    var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
        // b is in (anchor - 1 month, anchor + 1 month) => Why? Any theory or Math formula?
        anchor = a.clone().add(wholeMonthDiff, 'months'),
        anchor2,
        adjust;

    if (b - anchor < 0) {
        anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor - anchor2);
    } else {
        anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
        // linear across the month
        adjust = (b - anchor) / (anchor2 - anchor);
    }

    //check for negative zero, return zero if negative zero
    return -(wholeMonthDiff + adjust) || 0;
}

Ref:
https://github.com/moment/moment/blob/develop/src/lib/moment/diff.js

ondatachannel event never fires – WebRTC

Offer Side

let pc = new RTCPeerConnection({});
let dc = pc.createDataChannel("msg");
dc.onopen = function (e) {
  console.log("Channel Opened", e);
};
dc.onclose = function (e) {
  console.log("Channel closed");
};

let offer = await pc.createOffer();
await pc.setLocalDescription(offer);

socket.emit("offer", JSON.stringify(pc.localDescription));

socket.on("answer", function (sdp) {
  pc.setRemoteDescription(JSON.parse(sdp));
});

Answer Side

let pc = new RTCPeerConnection({});
pc.ondatachannel = function (e) {
  console.log(e);
};
socket.on("offer", async function (sdp) {
  await pc.setRemoteDescription(JSON.parse(sdp));
  let ans = await pc.createAnswer();
  pc.setLocalDescription(ans);
  socket.emit("answer", JSON.stringify(ans));
});

Ideally ondatachannel event should be fired.

Can someone tell me that why this is not working?

Thanks in advance 🙂

Source code

https://github.com/ats1999/RTSP-webRTC/tree/main/webRTC/data-channel

Do npm i to install the server side dependencies.

reactjs : sidebar does not reload when gones to inner pages

i have this sidebar in in app

when i have selected a link lets say differnt products and then ones more i click one the same link it does not reload

the issue is that when i select a link and inside the link i go to differnt componnet then when i click on the navLink i want to reach the page i started from

hope u understand my question

let me know if u dont 🙂

<ul style={styles.lists}>
          {this.props.siderbarcolor ? (
            <NavLink
              activeClassName="active3"
              className="porpssidebar"
              exact={true}
              to="/client"
            >
              <li style={styles.listItemActive}>
                <div>
                  <FontAwesomeIcon
                    icon={faThLarge}
                    style={{ marginRight: "1rem" }}
                  />
                </div>
                <div> Dashboard</div>
              </li>
            </NavLink>
          ) : (
            <NavLink activeClassName="active3" exact={true} to="/client">
              <li style={styles.listItemActive}>
                <div>
                  <FontAwesomeIcon
                    icon={faThLarge}
                    style={{ marginRight: "1rem" }}
                  />
                </div>
                <div> Dashboard </div>
              </li>
            </NavLink>
          )}
          <NavLink to="/product" activeClassName="active3">
            <li style={styles.listItem}>
              <div>
                <FontAwesomeIcon
                  icon={faUserMd}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div>Your product </div>
            </li>
          </NavLink>
          <NavLink activeClassName="active3" to="/cproducts" onClick={reloder()}>
            <li style={styles.listItem}>
              {console.log("dada")}
              <div>
                <FontAwesomeIcon
                  icon={faBriefcaseMedical}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div> differnt products</div>
            </li>
          </NavLink>

        
          <NavLink to="/meassger" activeClassName="active3">
            {/* <li style={styles.listItem}></li> */}
            <li style={styles.listItem}>
              <div>
                <FontAwesomeIcon icon={faSms} style={{ marginRight: "1rem" }} />
              </div>
              <div>Messages</div>
            </li>
          </NavLink>
          <NavLink to="/cproduct" activeClassName="active3">
            <li style={styles.listItem}>
              <div>
                <FontAwesomeIcon
                  icon={faQrcode}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div>serch product</div>
            </li>
          </NavLink>
        </ul>

querySelectorAll doesn’t capture all elements

I am trying to scan and manipulate DOM of a webpage the following Code:

var elements = document.querySelectorAll('*');
for (var i = 0; i < elements.length; i++) {
   if (!elements[i].firstElementChild) { 
       if (elements[i].innerHTML != "" ){ 
           elements[i].innerHTML = "abc_"+ elements[i].innerHTML+"_123";
       }
   }
}

While it works well on many pages, it is not picking up all the elements on a specific page that is my real target. On that page, it captures and edit strings of few elements, but not all.
I have also tried using getElementsByTagName()

The elements that are not captured have an XPath such as:

/html/body/div[4]/div[2]/div/div[2]/div/div/div/div/div[1]/div/div[2]/nav/div/div[1]/div/span/div

I also noticed “flex” written in front for these elements.

Any idea what am I doing wrong?

Cannot pass data to PhpMyAdmin by ajax

Index.php

This is part of my Index.php code, I cannot pass data to the file “action/viewupdate.php” using ajax.

                                    <tr>
                                        <td><?php echo $row['word'] ?></td>
                                        <td><?php echo $row['comment'] ?></td>
                                        <td><?php echo $row['viewno'] ?>
                                            <Span id="view_update<?php echo $count; ?>" style="display:none;font-weight:1000;color:green;font-size:12px"></Span>
                                        </td>
                                        <form action="" method="post" id="viewupdate<?php echo $count; ?>">
                                            <td><input type='button' name='viewupdate' value='Update' data-action="viewupdate<?php echo $count; ?>" class="button" /></td>
                                            <input type="hidden" id="userselectchannel<?php echo $count; ?>" name="userselectchannel<?php echo $count; ?>" value="<?php echo $row['videoline'] ?>">
                                            <input type="hidden" id="updateno<?php echo $count; ?>" name="updateno<?php echo $count; ?>" value="">
                                            <td style="display:none" id="saveupdateclm<?php echo $count; ?>"><input id="saveupdatebtn<?php echo $count; ?>" type='button' name='saveupdate<?php echo $count; ?>' value='Save**strong text**' data-action="saveupdate<?php echo $count; ?>" class="confirmbutton" /></td>
                                        </form>
                                    </tr>
                                    <script>
                                        $('#saveupdatebtn<?php echo $count; ?>').click(function() {
                                            var updateno1 = $('#updateno<?php echo $count; ?>').val();
                                            var userselectchannel1 = $('#userselectchannel<?php echo $count; ?>').val();
                                            var username1 = "<?php echo $_SESSION['nick_name']; ?>";
                                            /* alert(updateno + "n" + userselectchannel + "n" + username); */
                                            $.ajax({
                                                url: 'action/viewupdate.php',
                                                type: 'POST',
                                                data: {
                                                    "updateno": updateno1,
                                                    "userselectchannel": userselectchannel1,
                                                    "username": username1
                                                },
                                                cache: false,
                                                success: function(msg) {
                                                    console.log(data);
                                                    var x = document.getElementById("errorpopup2");
                                                    x.innerHTML = "<div style='color:#21ff21;'>Video <?php echo $count ?>Views update successfully</div>";
                                                    x.className = "show";
                                                    setTimeout(function() {
                                                        x.className = x.className.replace("show", "");
                                                    }, 3000);

                                                    $("#saveupdatebtn<?php echo $count; ?>").attr("disabled", "disabled");
                                                    $('#saveupdatebtn<?php echo $count; ?>').css('cursor', 'not-allowed');
                                                    return false;
                                                },
                                                error: function(msg) {
                                                    var x = document.getElementById("errorpopup2");
                                                    x.innerHTML = "Unknown Error Occured";
                                                    x.className = "show";
                                                    setTimeout(function() {
                                                        x.className = x.className.replace("show", "");
                                                    }, 3000);
                                                    return false;
                                                }

                                            });
                                        });

Viewupdate.php

<?php 
include_once "../../system/connect.php";
$updateno=$_POST['updateno'];
$userselectchannel=$_POST['userselectchannel'];
$username=$_POST['username'];
$time = date('Y-m-d H:i:s');
$updatetitle = $updateno;
$sql = "INSERT INTO `pagecontent_update`(`update-user`, `update-time`, `update-info`) 
VALUES ('$username','$time','$updatetitle')";
if (mysqli_query($link, $sql)) {
    echo json_encode(array("statusCode"=>200));
} 
else {
    echo json_encode(array("statusCode"=>201));
}
?>

PhpMyAdmin Screenshot
https://drive.google.com/file/d/1NcTYZNWhFMSQZMCZiNrTcfX-MPN4UGnT/view?usp=sharing

As the picture shown, data cannot pass to Viewupdate.php using ajax. As I wish that when user press the submit button, the data will stored into the database without refresh. Thx a lot.
If you need more information, please contact me at any time.

Javascript Interactjs – Delete div item on drop in dropzone

I’m trying to delete an item when being dropped in the dropzone that serves as bin. The tricky part here is that the dropzone must be in position:fixed and initially the draggable item is in position:relative. I think this causes the dropzone not to be able to detect when something is being dropped when the draggable is in a different position. I tried to fix this by changing position:absolute to draggable when item is being dragged but inevitably, the draggable overlaps the dropzone. How do I make this work?

/**
* 
* 
* ineracjs
* drag and drop
* 
* 
*/
function interactJs(){

var element = document.querySelector('.draggable');

var x = 0; var y = 0

interact(element)
.resizable({
// resize from all edges and corners
edges: { left: true, right: true, bottom: true, top: true },

listeners: {
move (event) {
var target = event.target
var x = (parseFloat(target.getAttribute('data-x')) || 0)
var y = (parseFloat(target.getAttribute('data-y')) || 0)

// update the element's style
target.style.width = event.rect.width + 'px'
target.style.height = event.rect.height + 'px'

// translate when resizing from top or left edges
x += event.deltaRect.left
y += event.deltaRect.top

target.style.transform = 'translate(' + x + 'px,' + y + 'px)'

target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
target.textContent = Math.round(event.rect.width) + 'u00D7' + Math.round(event.rect.height)
}
},
modifiers: [
// keep the edges inside the parent
interact.modifiers.restrictEdges({
outer: 'parent'
}),

// minimum size
interact.modifiers.restrictSize({
min: { width: 100, height: 50 }
})
],

inertia: true
})
.draggable({
modifiers: [
interact.modifiers.snap({
targets: [
interact.snappers.grid({ x: 30, y: 30 })
],
range: Infinity,
relativePoints: [ { x: 0, y: 0 } ]
}),
interact.modifiers.restrict({
restriction: element.parentNode,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 },
endOnly: true
})
],
inertia: true
})
.on('dragmove', function (event) {
x += event.dx
y += event.dy

event.target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
event.target.style.position = 'absolute';
})


/**
* 
* 
* delete
* dropzone
* 
*/
var bin = document.querySelector('.element-trash');

interact(bin)
.dropzone({
accept: '.draggable',
// Require a 75% element overlap for a drop to be possible
overlap: 0.75,
ondrop: function (event) {

$(event.target).remove();// remove from DOM

console.log(event.target);
}
})
.on('dropactivate', function (event) {
event.target.classList.add('drop-activated')
})
}interactJs();
.element-trash{
    height: 100%;
    color: white;
    background: red;
    padding: 1%;
    width: 120px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    overflow-x: hidden;
    transition: 0.5s;
    /* padding-top: 60px; */
}
#main{
padding: 0px !important;
margin-left: 120px;
}
#main{
  background-color: #eceef0;
}
#main {
  transition: margin-left .5s;
  height: 100% !important;
  /*padding: 16px;*/
  }
  .draggable {
  width: 10%;
  min-height: 6.5em;
  background-color: #29e !important;
  color: white;
  border-radius: 0.75em;
  padding: 4%;
  touch-action: none;
  user-select: none;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--ineractjs-->
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>

<div class='element-trash'>Drop to delete</div>

<div id='main'>

<div class='draggable'>Drag me</div>

</div>